2013-01-19 44 views
-2

所以我有文件:Python的文件列出

Ben cat 15 
John dog 17 
Harry hamster 3 

如何讓3名名單:

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

我已經嘗試了一切,但我還沒有找到一個解決辦法呢。

我使用Python 3.3.0

+1

你能表現出你已經嘗試過什麼的例子嗎? –

+0

另外,你是否試圖在單獨的變量或列表中創建3個列表? –

+0

@DavidRobinson我試圖分裂和readlines等 –

回答

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

它給出了錯誤:ValueError:解壓縮的值太多(預計3) –

+2

@JohnSmith:如果您的輸入文件是上面提到的,則不需要。你的文件的實際內容是什麼? –

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] 
+1

再次閱讀問題。這不是用戶要求的結果。 –

+0

@DavidRobinson現在,所以你的評論已經過時了。 – kojiro

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

我不確定它是否與OP的所需輸出相匹配。 – 2013-01-19 20:58:46

+0

OP專門詢問三個單獨的列表,而不是列表的列表。 – 2013-01-19 21:05:57

+0

@Mike:很好,謝謝。固定。 – NPE