[英]How to append lines from text file to multiple lists in python 3x
[英]Making lists from multiple lines in a text file (Python)
我試圖將文本文件轉換為多個列表,但我不確定如何,例如文本文件是:
Bob 16 Green
Sam 19 Blue
Sally 18 Brown
然后我想制作三個清單,
[Bob, Sam, Sally] , [16, 19, 18], [Green, Blue, Brown]
謝謝
使用生成器理解將令牌保持為字符串(不轉換整數或任何東西):
迭代文件/文本行,拆分單詞並將單詞列表zip
在一起:這將按您希望的方式“轉置”列表:
f = """Bob 16 Green
Sam 19 Blue
Sally 18 Brown""".splitlines()
print (list(zip(*(line.split() for line in f))))
結果(作為元組列表):
[('Bob', 'Sam', 'Sally'), ('16', '19', '18'), ('Green', 'Blue', 'Brown')]
*
解壓縮外部生成器理解作為zip
參數。 split
結果由zip
處理。
即使使用簡單的map
,避免了發電機表達,因為我們已經split
得心應手,( str.split(x)
是功能性符號x.split()
甚至要稍快一些):
print (list(zip(*map(str.split,f))))
請注意,我的示例是獨立的,但您可以通過文件句柄替換f
。
假設您將文件作為字符串加載,這是一個簡單的oneliner:
list(zip(*[line.split(' ') for line in filecontent.split('\n')]))
我首先將它拆分為所有新行,每行所有空格,然后翻轉它( zip
-operator)
下面的代碼可以滿足您的需求:
names = []
ages = []
fav_color = []
flist=open('myfile.txt','r').read().split('\n')
for line in flist:
names.append(line.split(' ')[0])
ages.append(line.split(' ')[1])
fav_color.append(line.split(' ')[2])
print(names)
print(ages)
print(fav_color)
lines.txt包含文本內容:
*
Bob 16 Green
Sam 19 Blue
Sally 18 Brown
*
Python代碼:
with open ("lines.txt", "r") as myfile:
data = myfile.readlines()
for line in data:
list = [word for word in line.split()]
print list
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.