2015-10-14 36 views
2

我有一個帶有數據的文本文件。例如,我想打印出「動物」的所有值。所以當選擇「動物」時,會打印出「猴子」,「大象」和「狗」。它有點作用,但它只打印出第一個值。例如,如果我選擇「動物」,它只打印猴子。在文件/列表中打印出相同值的索引

有沒有辦法讓它打印出它們全部?也許有更好的方法來做到這一點?

Data2.txt:

Adidas, shoe 
Monkey, animal 
Soup, food 
Elephant, animal 
Dog, animal 
Taco, food 

file = open('data2.txt') 
data = file.readlines 

stuffs = [] 
types = [] 


for line in data(): 
line = line.strip() 
stuff, type = line.split(', ') 
stuffs.append(stuff) 
types.append(type) 

animals = types.index('animal') 
print (stuffs[animals]) 
+0

什麼是與您當前密碼的問題?它做了什麼,以及它與你想要做的有什麼不同? – jonrsharpe

回答

1

你填充你的列表的方式,你有一個動物列表,和一個相應的類型,在同一個位置。使用index,你只會得到第一場比賽,但你需要全部。

一種方法是使用zip來迭代動物和類型對,並在類型正確的地方打印每個動物。

for s, t in zip(stuffs, types): 
    if t == "animal": 
     print(s) 

或者你可以使用列表理解收集所有的動物名單:

>>> [s for s, t in zip(stuffs, types) if t == "animal"] 
['Monkey', 'Elephant', 'Dog'] 

或者改變您存儲數據的方式。例如,而不必與相應指數和荏苒這些列表返回到對一個列表兩個列表,你可以創建對列表入手:

pairs = [] 
for line in data(): 
    line = line.strip() 
    pairs.append(line.split(', ')) 

print([s for s, t in pairs if t == "animal"]) 

甚至使用字典,地圖類型的東西,正如其他一些答案中的建議。

+0

謝謝!第一個很容易理解! – saltcracker

1

你需要通過類型的循環,因爲types.index( '動物')將只返回你的第一個。一旦你找到索引,你可以找到相應的索引。試試這個:

i = 0 
for type in types: 
    if (type == 'animal'): 
    print (stuffs[i]) 
    i = i + 1 
+0

如何爲我輸入enumerate(types):? –

+0

我敢肯定,這也很有效,但我很明確 – ergonaut

+1

@ergonaut,你更重新發明輪子 –

1

我想一個更好的主意是使用一個字典:

file = open('data2.txt') 
data = file.readlines 

categories = {} 

for line in data(): 
line = line.strip() 
stuff, type = line.split(', ') 
categories.setdefault(type, []).append(stuff) 

print (categories['animal']) 
1

使用collections.defaultdict到組的類型和csv module分析文件:

import csv 
from collections import defaultdict 
with open("test.txt") as f: 
    # create rows splitting on commas 
    r = csv.reader(f, skipinitialspace=True) 
    # create dict to store all the types 
    d = defaultdict(list) 
    # v = row[0], k = row[1] 
    for v,k in r: 
     d[k].append(v) 

輸出:

defaultdict(<class 'list'>, {'shoe': ['Adidas'], 
          'food': ['Soup', 'Taco'], 
          'animal': ['Monkey', 'Elephant', 'Dog']}) 

然後只需鍵查找:

print(d["animal"]) 
print(d["shoe"]) 

['Monkey', 'Elephant'] 
['Adidas'] 

你永遠不要需要調用readlines方法,除非你真正想要的清單,你可能會遍歷文件對象或者簡單地將其傳遞給csv模塊和迭代讀者對象在上面的代碼中。

+0

出於某種原因,'動物'出現兩次在你的字典。可能是數據文件中的一個雜散空間......猜猜'csv.reader'沒有'去掉' –

+0

@tobias_k,你說得對,這很奇怪,因爲'skipinitialspace = True'應該已經刪除了前導空間。我將不得不做一些調查 –

+0

但這是一個尾隨空間,而不是領先的空間。 ;-) –

0

使用numpy的是這樣的:

import numpy as np 

a = np.loadtxt("myFile") 

#Then it's simple! 

a[a[:,1] == 'animal'][0] 
+0

請解釋downvote – farhawa

+1

這不是我,但你假設他們知道numpy是什麼,以及那個神祕的線正在做什麼。 – ergonaut

1
d = {} 
with open('data','r') as f: 
    for line in f: 
     le, r = line.split(',') 
     d.setdefault(r.strip(),[]).append(le.strip()) 

for k,v in d.items(): 
    print(k,v) 

shoe ['Adidas'] 
food ['Soup', 'Taco'] 
animal ['Monkey', 'Elephant', 'Dog']