[英]making a list of lists from a file
I want to make a function that receives a file of several lines, for example:我想制作一个 function 来接收多行文件,例如:
A B 1
C D 2
E F 3
and returns a list of lists like this: [['A', 'B', '1'], ['C', 'D', '2'], ['E', 'F', '3']]并返回这样的列表列表:[['A', 'B', '1'], ['C', 'D', '2'], ['E', 'F', '3' ]]
This is the code I tried:这是我试过的代码:
def f(filename: str) -> list:
with open(filename,'r') as file:
content=file.readlines()
file.close()
for i in range(len(content)):
l=[list(content[i].split(" "))]
return l
but when I call the file I get only: [['A', 'B', '1']]但是当我调用文件时,我只得到:[['A', 'B', '1']]
How can I fix it please?请问我该如何解决?
This is one way you could do it:这是您可以做到的一种方式:
abc.txt: abc.txt:
A B 1
C D 2
E F 3
Code:代码:
def f(filename: str) -> list:
with open(filename,'r') as file:
return([x.split() for x in file])
print(f("abc.txt"))
Result:结果:
[['A', 'B', '1'], ['C', 'D', '2'], ['E', 'F', '3']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.