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

时间:2013-12-19 21:24:57

标签: python list while-loop counter

我需要一些帮助。我有以下两个清单:

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

4 个答案:

答案 0 :(得分:2)

您也可以尝试使用Counter

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

for line in sentences:
    print Counter([word for word in line.split() if word in color])

答案 1 :(得分:2)

使用Counter可能是最好的Pythonic(和最短)方式,但字符串还附带了一个内置的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)

答案 2 :(得分:0)

最简单的方法是在每个句子中查找每种颜色:

for sentence in sentences:
    count = 0
    for color in colors:
        for word in sentence.split(' '):
            if word == color:
                count + = 1
    print count

答案 3 :(得分:0)

您可以尝试这样的事情:

print [(s, sum(s.count(c) for c in colors)) for s in sentences]

输出

[('The green monkey age the blue egg', 2), 
 ('How many yellow monkey"s are in the green forest', 2)]

如果您想使用问题中列出的代码,则会出现3个错误:

  1. 你只需要循环一遍句子。
  2. 您需要将add替换为append。
  3. 您在添加/追加功能的末尾缺少一个括号。
  4. 以下固定代码:

    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:
        totals.append((sent, sum(sent.count(col) for col in color)))
    
    print totals
    
相关问题