繁体   English   中英

如何用字典计算元组元组中的所有元素?

[英]How to count all elements in a tuple of tuples with dictionary?

我有以下列表:

lst= (1,(1,2), 3, (3,4), 1, 3)

我想使用字典 function generate output 来计算每个值出现的次数,它看起来像这样:

{1:3, 2:1, 3:3, 4:1}

我不知道如何做到这一点。 谢谢!

以下是我的尝试:

def f(*args):
    for x in args:
        d = {x:args.count(x) for x in args}
    return d

对于任意深度的元组,您可以使用递归 function 进行展平:

def flatten_nested_tuples(tuples):
    for tup in tuples:
        if isinstance(tup, tuple):
            yield from flatten_nested_tuples(tup)
        else:
            yield tup

yield from x语法等价于for item in x: yield item 它只是创建生成器的一种更短的方法。 您可以查看此答案和此答案,以获取有关生成器和yield关键字的更多信息。

要计数,我们可以使用collections.Counter来计算扁平元组:

from collections import Counter

lst= (1,(1,2), 3, (3,4), 1, 3)

print(Counter(flatten_nested_tuples(lst)))

Output:

Counter({1: 3, 3: 3, 2: 1, 4: 1})

注意: Counterdict的子类,因此您可以将其视为常规 dict。

如果您想在没有任何模块的情况下计算自己,则必须对自己进行0初始化:

counts = {}
for item in flatten_nested_tuples(lst):
    counts[item] = counts.get(item, 0) + 1

print(counts)
# {1: 3, 2: 1, 3: 3, 4: 1}

或者不使用dict.get()

counts = {}
for item in flatten_nested_tuples(lst):
    if item not in counts:
        counts[item] = 0
    counts[item] += 1

print(counts)
# {1: 3, 2: 1, 3: 3, 4: 1}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM