3 回答

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超9個贊
在這里嘗試一下,首先拆分每一行,您將獲得一個數(shù)字列表作為字符串,因此map可以使用函數(shù)將其更改為int:
with open('file.txt', 'r') as f:
k = [list(map(int,i.split())) for i in f.readlines()]
print(k)

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超3個贊
你并不需要應(yīng)用str.strip和str.split獨(dú)立。相反,將它們組合在一個操作中。列表推導(dǎo)式是通過定義一個列表元素,然后在循環(huán)上進(jìn)行迭代來構(gòu)建的for。
另請注意,str.strip不帶參數(shù)將與\n空格一樣處理。同樣,str.split沒有參數(shù)的情況下也會被空格分隔。
from io import StringIO
x = StringIO("""3 8 6 9 4
4 3 0 8 6
2 8 3 6 9
3 7 9 0 3""")
# replace x with open('some_file.txt', 'r')
with x as grid:
list_of_lists = [[int(elm) for elm in line.strip().split()] for line in grid]
結(jié)果:
print(list_of_lists)
[[3, 8, 6, 9, 4],
[4, 3, 0, 8, 6],
[2, 8, 3, 6, 9],
[3, 7, 9, 0, 3]]
使用內(nèi)置功能,使用起來效率更高map:
list_of_lists = [list(map(int, line.strip().split())) for line in grid]
添加回答
舉報