说我有一个包含以下内容的文本文件:如何将每个文本文件行分隔为单独的列表?
Bob 15 M
John 16 M
Jen 15 F
我如何把它变成一个列表,该列表值:
listOne = ['Bob', '15', 'M']
listTwo = ['John', '16', 'M']
listThree = ['Jen', '15', 'F']
感谢
说我有一个包含以下内容的文本文件:如何将每个文本文件行分隔为单独的列表?
Bob 15 M
John 16 M
Jen 15 F
我如何把它变成一个列表,该列表值:
listOne = ['Bob', '15', 'M']
listTwo = ['John', '16', 'M']
listThree = ['Jen', '15', 'F']
感谢
只是拆分它并将其解压缩
bob, john, jen = [a.split() for a in open(file)]
非常好的一点。虽然它会被垃圾收集并关闭,但我们无法总是依靠解释器来做到这一点 – danidee
在CPython中,它通常会立即被垃圾收集;在其他Python实现中,它可能会停留一段时间。 –
用打开文件和分割():
with open('text.txt') as f:
strings = f.readlines()
data = [string.split() for string in strings]
不需要字符串。只需遍历文件对象。 –
with open('text.txt') as file:
lines = file.readlines() # Creates a list of lines
for line in lines:
line = line.split() # Split each line into list of "words"
这给你一个嵌套列表这可能是明智的。如果你迫切想3所列出,使用此:
evalvar = ""
count = 0
for line in lines:
count += 1
evalvar += "list"+str(count)+" = "+str(line)+";"
exec(evalvar) # Runs the evalvar which has
# code in it.
您可以在文件中适用string.split
每一行:
import string
with open('text.txt') as text:
result = map(string.split, text)
使用Python 3,您需要兑现的map
,否则文件没有按之前它关闭“吨得到阅读:
result = list(map(string.split, text))
然而,string.split
已被废弃,只适用于str
对象,正ot unicode
。一个更普遍的解决方案是创建一个列表理解:
result = [line.split() for line in text]
[字符串分割到Python的list(的可能的复制http://stackoverflow.com/questions/743806/split-string-into-a-列表在蟒蛇) –
你想3列表? – Tim
@PeterWood雅,Forgeted。 –