python - 打印文件/列表中相同值的索引

标签 python python-3.x

我有一个包含数据的文本文件。例如,我想打印出“动物”的所有值。因此,当选择“动物”时,它将打印出“猴子”、“大象”和“狗”。它有点工作,但它只打印出第一个值。例如,如果我选择“动物”,它只会打印出猴子。

有没有办法让它全部打印出来?也许有更好的方法来做到这一点?

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

最佳答案

填充列表的方式是,在相同的位置上有一个包含动物的列表和一个包含相应类型的列表。使用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"])

或者甚至使用字典,将类型映射到内容,正如其他一些答案中所建议的那样。

关于python - 打印文件/列表中相同值的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33132549/

相关文章:

python - 一个 Dataframe 的每一列的最大值和最小值

c# - 为什么在某些风格中,后视中的有限重复不起作用?

python - 将 hex 文件转换为 bin 文件

python - 移动友好测试脚本

python - 删除 pandas 数据框中具有多个关联的条目?

python - 使用循环在 plotly 中定义多个 y 轴

python - 在 Python 中通过三元运算符传递函数参数

python - 占位符类方法 Python 3

python - 使用 astype(int) 将 numpy 数组转换为整数在 Python 3.6 上不起作用

python - 如何从 PyListObject 获取 `pop` 元素?