简体   繁体   中英

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:

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 . results of split are processed by 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):

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

Note that my example is standalone, but you can replace f by a file handle all right.

A simple oneliner, assuming you load the file as a string:

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)

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:

*

Bob 16 Green
Sam 19 Blue
Sally 18 Brown

*

Python code:

with open ("lines.txt", "r") as myfile:
  data = myfile.readlines()
  for line in data:
    list = [word for word in line.split()]
    print list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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