gpt4 book ai didi

python - while循环计数器比较两个列表

转载 作者:行者123 更新时间:2023-11-28 22:52:13 24 4
gpt4 key购买 nike

我需要一些帮助。我有以下两个列表:

sentences = ['The green monkey green age the blue egg','How many yellow green monkey"s are in the green forest']
color =['orange', 'green', 'yellow', 'violet', 'blue']

totals = []

for sent in sentences:
print sent
for sent in sentences:
totals.add((sent, sum(sent.count(col) for col in color))

我的目标是计算颜色元素在句子中任何给定元素中出现的次数。所以我的输出将包含每个句子元素和存在的颜色元素的计数。对此的任何帮助将不胜感激。我是初学者,目前为止很喜欢 python :)

最佳答案

使用 Counter 可能是最符合 Python 风格(也是最短)的方法,但是字符串还带有一个内置的 count 方法,您可以使用它:

color =['orange', 'green', 'yellow', 'violet', 'blue']
sentences = ['The green monkey age the blue egg', 'How many yellow monkey"s are in the green forest']

for sent in sentences:
print sent
for col in color:
print "", col, sent.count(col)

输出:

The green monkey age the blue egg
orange 0
green 1
yellow 0
violet 0
blue 1
How many yellow monkey"s are in the green forest
orange 0
green 1
yellow 1
violet 0
blue 0

编辑:

如果您只想要句子中颜色总数旁边的句子,请将最后一个 for 循环替换为求和和 list comprehension :

for sent in sentences:
print sent, sum(sent.count(col) for col in color)

关于python - while循环计数器比较两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20691976/

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