1

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

0

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

-1

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)

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.