简体   繁体   English

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

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

I have the following list:我有以下列表:

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

and I want to use the dictionary function generate output that will count the number of times each value occurs such that it would look like this:我想使用字典 function generate output 来计算每个值出现的次数,它看起来像这样:

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

I am lost on how to do this.我不知道如何做到这一点。 Thank you!谢谢!

Below is my attempt:以下是我的尝试:

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

For arbitrary depth tuples, you could use a recursive function for flattening:对于任意深度的元组,您可以使用递归 function 进行展平:

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

The yield from x syntax is equivalent to the for item in x: yield item . yield from x语法等价于for item in x: yield item Its just a shorter way to create generators.它只是创建生成器的一种更短的方法。 You can have a look at this answer and this answer for more information about generators and the yield keyword.您可以查看此答案和此答案,以获取有关生成器和yield关键字的更多信息。

To count we can use collections.Counter to count the flattened tuples:要计数,我们可以使用collections.Counter来计算扁平元组:

from collections import Counter

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

print(Counter(flatten_nested_tuples(lst)))

Output: Output:

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

Note: Counter is a subclass of dict , so you can treat it like a regular dict.注意: Counterdict的子类,因此您可以将其视为常规 dict。

If you want to count yourself without any modules, you have to do the 0 initializing yourself:如果您想在没有任何模块的情况下计算自己,则必须对自己进行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}

Or without using dict.get() :或者不使用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