【问题标题】:How to count how many times a word in a list appeared in-another list如何统计一个列表中的单词在另一个列表中出现了多少次
【发布时间】:2022-12-03 14:27:14
【问题描述】:

我有 2 个列表,我想看看列表 1 中有多少文本在列表 2 中,但我真的不知道有什么方法可以将它们组合起来,输出未求和,我尝试了 sum 方法,但确实如此它为所有单词计算而不是每个单词。

代码:

l1 = ['hello', 'hi']
l2 = ['hey', 'hi', 'hello', 'hello']
for i in l2:
    print(f'{l1.count(i)}: {i}')

输出:

0: hey
1: hi
1: hello
1: hello

我想要的是更像这样的东西:

0: hey
1: hi
2: hello

【问题讨论】:

  • 首先创建代码来计算单个单词在列表中出现的次数。一旦有了正确的答案,就可以在此基础上进行构建。

标签: python list for-loop count sum


【解决方案1】:

您可以使用 in 运算符来检查 l1 中的每个元素是否都在 l2 中。然后,您可以使用 Counter 对象来计算 l1 中每个元素在 l2 中出现的次数。

这是一个例子:

from collections import Counter

l1 = ['hello', 'hi']
l2 = ['hey', 'hi', 'hello', 'hello']

# Create a Counter object to count the occurrences of each element in l1 that is also in l2
counter = Counter()

# Loop over each element in l1 and check if it is in l2
for element in l1:
    if element in l2:
        # If the element is in l2, increment the count for that element
        counter[element] += 1

# Print the count for each element
for element, count in counter.items():
    print(f'{count}: {element}')

这将打印以下输出:

1: hi
2: hello

【讨论】:

    【解决方案2】:

    如果要计算 l1 中的每个单词在 l2 中出现的次数,可以使用字典来跟踪每个单词的次数。这是一种可能的方法:

    l1 = ['hello', 'hi']
    l2 = ['hey', 'hi', 'hello', 'hello']
    
    # Create an empty dictionary
    counts = {}
    
    # Loop through each word in l1
    for word in l1:
        # Initialize the count for this word to 0
        counts[word] = 0
        # Loop through each word in l2
        for word2 in l2:
            # If the word from l1 appears in l2, increment the count
            if word == word2:
                counts[word] += 1
    
    # Print the counts for each word
    for word in l1:
        print(f'{counts[word]}: {word}')
    

    此代码将打印以下输出: 2: hello 1: hi 这种方法允许您计算 l2 中 l1 中每个单词的出现次数,并以所需格式打印计数。您可以进一步自定义代码以满足您的特定需求。例如,您可以根据您的要求按值对计数进行排序或以不同的顺序打印计数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-30
      • 1970-01-01
      • 2021-05-09
      • 1970-01-01
      • 1970-01-01
      • 2020-05-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多