gpt4 book ai didi

python - 计算一个列表中每个值出现在第二个列表中的次数

转载 作者:行者123 更新时间:2023-12-01 04:56:11 25 4
gpt4 key购买 nike

我有两个列表。首先是三次旅行中每次看到的动物列表。其次是动物类型列表。

In [1]:

animals_seen = ['cat dog mouse', 'cat dog', 'cat']
animal_types = ['cat', 'dog', 'mouse']

我想要查看某种动物被看到的次数。在这种情况下:

seen_count = [3, 2, 1]

即猫出现3次,狗出现2次,老鼠出现1次。

我的策略是循环遍历每种动物类型,并且对于每次行程的每个循环,如果看到该动物类型,则添加 1,然后将该值附加到名为 saw_count 的新列表中。

这是我的代码:

In [2]:

seen_count = []

for animal in animal_types:
for seen in animals_seen:
count = 0
if animal in seen:
count = count + 1
else:
count = count + 0
seen_count.append(count)

print(seen_count)

但是,输出没有意义:

Out[4]:
[1, 0, 0]

我做错了什么?有没有更简单的方法?

最佳答案

这是 defaultdict完美用法:

from collections import defaultdict

animals_seen = ['cat dog mouse', 'cat dog', 'cat']
animal_types = ['cat', 'dog', 'mouse']

seen_count = defaultdict(int)

for animal in animal_types:
for seen in animals_seen:
if animal in seen:
seen_count[animal] += 1

print(seen_count)

给予:

{'mouse': 1, 'dog': 2, 'cat': 3}

关于python - 计算一个列表中每个值出现在第二个列表中的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27335407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com