【问题标题】:Counting the number of lists that contain an element in Python在 Python 中计算包含元素的列表的数量
【发布时间】:2013-07-13 20:17:24
【问题描述】:

如何创建一个列表,其中包含一个元素在多个列表中出现的次数。例如我有这些列表:

list1 = ['apples','oranges','grape']
list2 = ['oranges, 'oranges', 'pear']
list3 = ['strawberries','bananas','apples']
list4 = [list1,list2,list3]

我想计算包含每个元素的文档数量并将其放入字典中,所以对于苹果^和橙子,我得到了这个:

term['apples'] = 2
term['oranges'] = 2   #not 3

【问题讨论】:

  • term['apples'] 暗示使用字典。
  • “橙子”的计数需要多少? 2个还是3个?
  • 2...文档数:)

标签: python list dictionary count


【解决方案1】:
>>> [el for lst in [set(L) for L in list4] for el in lst].count('apples')
2
>>> [el for lst in [set(L) for L in list4] for el in lst].count('oranges')
2

如果您希望最终结构为字典,则可以使用字典推导式从展平的集合列表中创建直方图:

>>> list4sets = [set(L) for L in list4]
>>> list4flat = [el for lst in list4sets for el in lst]
>>> term = {el: list4flat.count(el) for el in list4flat}
>>> term['apples']
2
>>> term['oranges']
2

【讨论】:

  • el 不是列表吗?如何将它用作字典中的键?
【解决方案2】:

使用collections.Counter

from collections import Counter
terms = Counter( x for lst in list4 for x in lst )
terms
=> Counter({'oranges': 3, 'apples': 2, 'grape': 1, 'bananas': 1, 'pear': 1, 'strawberries': 1})
terms['apples']
=> 2

正如@Stuart 所指出的,您还可以使用chain.from_iterable,以避免生成器表达式中看起来很尴尬的双循环(即for lst in list4 for x in lst)。

编辑:另一个很酷的技巧是取Counters 的总和(受this 著名答案的启发),例如:

sum(( Counter(lst) for lst in list4 ), Counter())

【讨论】:

  • 我认为 list4 不应该被包括在内。
  • 谢谢,但问题是,我想获取该术语出现在列表中的数量,例如,如果列表中有 5 次,它仍应算作一个计数...术语[ 'apple'] 给出这个词在所有文档中出现的次数,而不是包含 apple 的文档的数量
  • 啊,在这种情况下,使用sets 代替列表来删除重复项。例如list4 = [ set(list1), set(list2), set(list3) ]。这样,答案仍然有效。
【解决方案3】:
print (list1 + list2 + list3).count('apples')

或者如果您已经在list4 中编译了所有列表,您可以使用itertools.chain 作为链接它们的快捷方式:

from itertools import chain
print list(chain.from_iterable(list4)).count('apples')

编辑:或者您可以不使用itertools

print sum(list4, []).count('apples') 

如果出于某种原因您想复制collections.Counter,您可以轻松...

all_lists = sum(list4, [])
print dict((k, all_lists.count(k)) for k in set(all_lists))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-20
    • 2021-03-09
    • 2020-02-03
    • 2023-02-25
    • 2010-10-10
    • 1970-01-01
    • 2016-11-07
    相关资源
    最近更新 更多