-2

所以我有文件:

Ben cat 15
John dog 17
Harry hamster 3

如何制作 3 个列表:

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

我已经尝试了一切,但我还没有找到解决方案。

我正在使用 Python 3.3.0

4

3 回答 3

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))
于 2013-01-19T20:49:59.007 回答
1

以下:

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

产生:

['Ben', 'John', 'Harry']
['cat', 'dog', 'hamster']
['15', '17', '3']
于 2013-01-19T20:52:52.557 回答
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]
于 2013-01-19T20:49:14.600 回答