Python文件列表



我输入file:

Ben cat 15
John dog 17
Harry hamster 3

如何制作3个列表:

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

我什么都试过了,但还没有找到解决办法。

我正在使用Python 3.3.0

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))

以下内容:

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']
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]

相关内容

  • 没有找到相关文章

最新更新