【问题标题】:Python count in a sublist in a nest list嵌套列表中的子列表中的 Python 计数
【发布时间】:2013-03-01 06:20:44
【问题描述】:
x = [['a', 'b', 'c'], ['a', 'c', 'd'], ['e', 'f', 'f']]

假设我们有一个包含随机 str 字母的列表。 我如何创建一个函数,以便它告诉我字母“a”出现了多少次,在这种情况下为 2。或任何其他字母,如“b”出现一次,“f”出现两次。等等 谢谢!

【问题讨论】:

  • sum(1 for e in x if 'a' in e)
  • 你能帮我澄清一下吗? :/ 我对 python 有点陌生。
  • @Abhijit 或只是sum('a' in e for e in x),至少对我来说更容易阅读(作为“加起来其中有多少有'a'”)。

标签: python


【解决方案1】:

您可以展平列表并使用collections.Counter

>>> import collections
>>> x = [['a', 'b', 'c'], ['a', 'c', 'd'], ['e', 'f', 'f']]
>>> d = collections.Counter(e for sublist in x for e in sublist)
>>> d
Counter({'a': 2, 'c': 2, 'f': 2, 'b': 1, 'e': 1, 'd': 1})
>>> d['a']
2

【讨论】:

    【解决方案2】:
    import itertools, collections
    result = collections.defaultdict(int)
    for i in itertools.chain(*x):
        result[i] += 1
    

    这将创建result 作为字典,其中字符作为键,它们的计数作为值。

    【讨论】:

    • 你也可以只做collections.Counter(itertools.chain(*x)),因为Counter类和你刚才做的一样。
    • @Blender 谢谢;我以为Counter 是 python 3.1+,但我在文档中看到它说 2.7。不管我测试的电脑是 2.6 :/
    • 最好使用itertools.chain(*x)而不是chain.from_iterable(x)
    【解决方案3】:

    仅供参考,您可以使用sum() 来展平单个嵌套列表。

    >>> from collections import Counter
    >>>
    >>> x = [['a', 'b', 'c'], ['a', 'c', 'd'], ['e', 'f', 'f']]
    >>> c = Counter(sum(x, []))
    >>> c
    Counter({'a': 2, 'c': 2, 'f': 2, 'b': 1, 'e': 1, 'd': 1})
    

    但是,正如 Blender 和 John Clements 所说,itertools.chain.from_iterable() 可能更清楚。

    >>> from itertools import chain
    >>> c = Counter(chain.from_iterable(x)))
    >>> c
    Counter({'a': 2, 'c': 2, 'f': 2, 'b': 1, 'e': 1, 'd': 1})
    

    【讨论】:

    • chain 也可以更快一些,因为sum 构建了许多中间列表,而chain 没有构建。
    猜你喜欢
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多