Reputation: 43
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
Upvotes: 1
Views: 2117
Reputation: 7
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
Upvotes: -1
Reputation: 2884
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)
Upvotes: -1
Reputation: 140316
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.
Upvotes: 4
Reputation: 2502
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)
Upvotes: 1