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.