简体   繁体   English

从文本文件中的多行创建列表(Python)

[英]Making lists from multiple lines in a text file (Python)

I am trying to turn a text file into multiple lists but I am unsure how, say for example the text file is: 我试图将文本文件转换为多个列表,但我不确定如何,例如文本文件是:

Bob 16 Green
Sam 19 Blue
Sally 18 Brown

I then want to make three lists, 然后我想制作三个清单,

[Bob, Sam, Sally] , [16, 19, 18], [Green, Blue, Brown]

thanks 谢谢

Keeping tokens as strings (not converting integers or anything), using a generator comprehension: 使用生成器理解将令牌保持为字符串(不转换整数或任何东西):

Iterate on the file/text lines, split your words and zip the word lists together: that will "transpose" the lists the way you want: 迭代文件/文本行,拆分单词并将单词列表zip在一起:这将按您希望的方式“转置”列表:

f = """Bob 16 Green
Sam 19 Blue
Sally 18 Brown""".splitlines()

print (list(zip(*(line.split() for line in f))))

result (as a list of tuples): 结果(作为元组列表):

[('Bob', 'Sam', 'Sally'), ('16', '19', '18'), ('Green', 'Blue', 'Brown')]

* unpacks the outer generator comprehension as arguments of zip . *解压缩外部生成器理解作为zip参数。 results of split are processed by zip . split结果由zip处理。

Even simpler using map which avoids the generator expression since we have split handy, ( str.split(x) is the functional notation for x.split() ) (should even be slightly faster): 即使使用简单的map ,避免了发电机表达,因为我们已经split得心应手,( str.split(x)是功能性符号x.split()甚至要稍快一些):

print (list(zip(*map(str.split,f))))

Note that my example is standalone, but you can replace f by a file handle all right. 请注意,我的示例是独立的,但您可以通过文件句柄替换f

A simple oneliner, assuming you load the file as a string: 假设您将文件作为字符串加载,这是一个简单的oneliner:

list(zip(*[line.split(' ') for line in filecontent.split('\n')]))

I first split it at all the new lines, each of those at all of the spaces, and then flip it ( zip -operator) 我首先将它拆分为所有新行,每行所有空格,然后翻转它( zip -operator)

the code below does what you want: 下面的代码可以满足您的需求:

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 has the text contents: lines.txt包含文本内容:

* *

Bob 16 Green
Sam 19 Blue
Sally 18 Brown

* *

Python code: 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM