我試圖通過運行 C 可執行檔案從 python 代碼執行 C 檔案。下面是我的代碼:
import subprocess
import sys
dataset = sys.argv[1]
def func():
subprocess.run(['/home/dev/exec_file', dataset, 'outfile'])
f_result = []
f = open('outfile', "r")
content = f. read()
f_result.append(content)
print(f_result)
#print(content.rstrip('\n'))
return f_result
在這里,如果我簡單地寫,print(content.rstrip('\n'))那么它會給出如下輸出:
*,*,1,*,0
*,*,2,2,1
*,*,*,3,1
*,*,*,4,2
*,*,3,*,2
現在我想回傳一個串列串列。我的意思是它看起來像:
[['*', '*', '1', '*', '0'], ['*', '*', '2', '2', '1'], ['*', '*', '*', '3', '1'], ['*', '*', '*', '4', '2'], ['*', '*', '3', '*', '2']]
在我上面的方法print(f_result)中,輸出如下:['*,*,1,*,0\n*,*,2,2,1\n*,*,*,3,1\n*,*,*,4,2\n*,*,3,*,2\n']
我該怎么做并從中回傳串列串列?請幫忙。
uj5u.com熱心網友回復:
使用串列理解和str.split:
content = '*,*,1,*,0\n*,*,2,2,1\n*,*,*,3,1\n*,*,*,4,2\n*,*,3,*,2\n'
[l.split(',') for l in content.rstrip('\n').split('\n')]
輸出:
[['*', '*', '1', '*', '0'],
['*', '*', '2', '2', '1'],
['*', '*', '*', '3', '1'],
['*', '*', '*', '4', '2'],
['*', '*', '3', '*', '2']]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/375905.html
