如果我有这样的文本文件:
Hello World
How are you?
Bye World
我将如何将其读取为多维数组,如下所示:
[["Hello", "World"],
["How", "are", "you?"],
["Bye" "World"]]
我试过了:
textFile = open("textFile.txt")
lines = textFile.readlines()
for line in lines:
line = lines.split(" ")
但是它只是返回:
["Hello World\n", "How are you?\n", "Bye World"]
如何将文件读入多维数组?
最佳答案
使用列表推导和str.split
:
with open("textFile.txt") as textFile:
lines = [line.split() for line in textFile]
演示:
>>> with open("textFile.txt") as textFile:
lines = [line.split() for line in textFile]
...
>>> lines
[['Hello', 'World'], ['How', 'are', 'you?'], ['Bye', 'World']]
with
statement:关于python - 使用Python将文件读取到多维数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19056125/