[英]Print out indexes of same values in file/list
我有一个带有数据的文本文件。 例如,我要打印出“动物”的所有值。 因此,当选择“动物”时,它将打印出“猴子”,“大象”和“狗”。 它有些起作用,但是只打印出第一个值。 例如,如果我选择“动物”,则仅打印出“猴子”。
有没有办法使它们全部打印出来? 也许有更好的方法可以做到这一点?
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])
您需要遍历类型,因为types.index('animal')只会返回您的第一个。 一旦找到索引,就可以在材料中找到相应的索引。 尝试这个:
i = 0
for type in types:
if (type == 'animal'):
print (stuffs[i])
i = i + 1
我认为更好的主意是使用dict:
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'])
使用collections.defaultdict对类型进行分组,然后使用csv模块来解析文件:
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模块并遍历Reader对象,如上面的代码。
填充列表的方式是,在同一位置有一个包含动物的列表,一个具有相应类型的列表。 使用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"])
甚至使用字典,将类型映射到内容,如其他一些答案中所建议的那样。
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']
通过以下方式使用numpy:
import numpy as np
a = np.loadtxt("myFile")
#Then it's simple!
a[a[:,1] == 'animal'][0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.