-2

So I have file:

Ben cat 15
John dog 17
Harry hamster 3

How to make 3 lists:

[Ben, John, Harry]
[cat, dog, hamster]
[15, 17, 3]

I have tried everything, but I haven't find a solution yet.

I am using Python 3.3.0

3 Answers3

1
with open("file.txt") as inf:
    # divide into tab delimited lines
    split_lines = [l[:-1].split() for l in inf]
    # create 3 lists using zip
    lst1, lst2, lst3 = map(list, zip(*split_lines))
David Robinson
  • 77,383
  • 16
  • 167
  • 187
1

The following:

ll = [l.split() for l in open('file.txt')]
l1, l2, l3 = map(list, zip(*ll))
print(l1)
print(l2)
print(l3)

produces:

['Ben', 'John', 'Harry']
['cat', 'dog', 'hamster']
['15', '17', '3']
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • I'm not sure this matches the desired output of the OP. –  Jan 19 '13 at 20:58
  • OP specifically asked for three separate lists, not a list of lists. –  Jan 19 '13 at 21:05
  • The inability of OP to go from a list of three lists to three separate lists is tangential to the question *and* why we can't have nice things. – kojiro Jan 19 '13 at 21:09
  • @Mike also, if you want to be pedantic about what OP asked for, he asked for two lists of barewords and one list of numbers. Unless there are objects named `Ben`, `John`, `Harry`, `cat`, `dog`, and `hamster` already in scope it's unlikely this is actually what he meant. I think @NPE's (and my) responses were reasonable. – kojiro Jan 19 '13 at 21:17
0
gsi-17382 ~ $ cat file
Ben cat 15
John dog 17
Harry hamster 3
gsi-17382 ~ $ python
Python 2.7.2 (default, Jun 20 2012, 16:23:33) 
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> zip(*[l.split() for l in open('file')])
[('Ben', 'John', 'Harry'), ('cat', 'dog', 'hamster'), ('15', '17', '3')]
>>> names, animals, numbers = map(list, zip(*[l.split() for l in open('file')]))
>>> numbers = map(int, numbers)
>>> names
['Ben', 'John', 'Harry']
>>> animals
['cat', 'dog', 'hamster']
>>> numbers
[15, 17, 3]
kojiro
  • 74,557
  • 19
  • 143
  • 201