-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

以下:

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 に答える
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 に答える
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 に答える