【问题标题】:Count occurrences of given words per each list in a tuple of lists计算列表元组中每个列表中给定单词的出现次数
【发布时间】:2021-02-17 07:44:41
【问题描述】:

我有一个标记化句子的列表,我想计算几个单词的集体出现: 例如:

example_list = (['hey', 'there', 'you', 'how', 'are', 'you'],
                ['i', 'am', 'fine', 'how', 'about', you],
                ['i', 'am', 'good'])

现在我想计算以下单词在每个列表中出现的次数并将分数附加到列表中

score = []
test = ['hey', 'you']

我尝试以下代码:

for i in range(len(test)):
   for j in range(len(example_list)):
       score1.append(example_list[j].count(test[i]))

并获得以下输出:

[1, 0, 0, 2, 1, 0]

而我想要输出:

[3, 1, 0]

有什么想法吗?

【问题讨论】:

    标签: python list count append


    【解决方案1】:

    只需使用传统的for 循环:

    example_list = (['hey', 'there', 'you', 'how', 'are', 'you'],
                    ['i', 'am', 'fine', 'how', 'about', 'you'],
                    ['i', 'am', 'good'])
    test = ['hey', 'you']
    score = []
    
    for lst in example_list:
        total = 0
        for word in test:
            total += lst.count(word)
        score.append(total)
    
    print(score)
    

    输出:

    [3, 1, 0]
    

    【讨论】:

      【解决方案2】:

      您可以使用带有sum 的嵌套列表推导来添加test 中所有元素的出现。

      此外,您可能希望从 test 构建一个 set 以便更快地查找:

      test = set(['hey', 'you'])
      
      [sum(s in test for s in l) for l in example_list]
      # [3, 1, 0]
      

      【讨论】:

        【解决方案3】:

        您可以在列表理解中使用sum

        example_list = (['hey', 'there', 'you', 'how', 'are', 'you'],
                        ['i', 'am', 'fine', 'how', 'about', 'you'],
                        ['i', 'am', 'good'])
        
        
        
        test = ['hey', 'you']
        
        
        score = [sum(s in test for s in lst) for lst in example_list]
        print(score)
        

        输出

        [3, 1, 0]
        

        如果test 足够大,请考虑使用集合。

        【讨论】:

        • 你是否也有一个聪明的方法来计算每个列表的嵌套长度?即该列表中有多少个单词?
        • @apol96 [len(lst) for lst in example_list]?
        【解决方案4】:

        您可以使用Counter 执行此任务:

        from collections import Counter
        
        
        counters = [Counter(l) for l in example_list]
        occurrences = [sum([c[word] for word in test if word in c]) for c in counters]
        
        print(occurrences) # [3, 1, 0]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-02-05
          • 1970-01-01
          • 1970-01-01
          • 2013-04-07
          • 2021-10-15
          • 2018-01-14
          • 1970-01-01
          相关资源
          最近更新 更多