3 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊
假設(shè)您沒有多余的空格:
with open('file') as f:
w, h = [int(x) for x in next(f).split()] # read first line
array = []
for line in f: # read rest of lines
array.append([int(x) for x in line.split()])
您可以將最后一個(gè)for循環(huán)壓縮為嵌套列表推導(dǎo):
with open('file') as f:
w, h = [int(x) for x in next(f).split()]
array = [[int(x) for x in line.split()] for line in f]

TA貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超7個(gè)贊
對(duì)我來(lái)說,這種看似簡(jiǎn)單的問題就是Python的全部意義所在。尤其是如果您來(lái)自像C ++這樣的語(yǔ)言,其中簡(jiǎn)單的文本解析可能會(huì)給您帶來(lái)麻煩,那么您將非常感激python可以為您提供的功能單位明智的解決方案。我將通過幾個(gè)內(nèi)置函數(shù)和一些生成器表達(dá)式使它保持非常簡(jiǎn)單。
你需要open(name, mode),myfile.readlines(),mystring.split(),int(myval),然后你可能會(huì)想使用幾個(gè)發(fā)電機(jī)來(lái)把它們放在一起的Python的方式。
# This opens a handle to your file, in 'r' read mode
file_handle = open('mynumbers.txt', 'r')
# Read in all the lines of your file into a list of lines
lines_list = file_handle.readlines()
# Extract dimensions from first line. Cast values to integers from strings.
cols, rows = (int(val) for val in lines_list[0].split())
# Do a double-nested list comprehension to get the rest of the data into your matrix
my_data = [[int(val) for val in line.split()] for line in lines_list[1:]]
在此處查找生成器表達(dá)式。它們確實(shí)可以將您的代碼簡(jiǎn)化為離散的功能單元!想象一下在C ++中用4行代碼做同樣的事情……那將是一個(gè)怪物。特別是列表生成器,當(dāng)我還是C ++時(shí),我一直希望自己擁有類似的東西,而且我常常最終會(huì)構(gòu)建自定義函數(shù)來(lái)構(gòu)造所需的每種數(shù)組。

TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超8個(gè)贊
不知道為什么需要w,h。如果實(shí)際上需要這些值,并且意味著僅應(yīng)讀取指定數(shù)量的行和列,則可以嘗試以下操作:
output = []
with open(r'c:\file.txt', 'r') as f:
w, h = map(int, f.readline().split())
tmp = []
for i, line in enumerate(f):
if i == h:
break
tmp.append(map(int, line.split()[:w]))
output.append(tmp)
添加回答
舉報(bào)