简体   繁体   中英

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)

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:

{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:

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 . 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.

To count we can use collections.Counter to count the flattened tuples:

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})

Note: Counter is a subclass of dict , so you can treat it like a regular dict.

If you want to count yourself without any modules, you have to do the 0 initializing yourself:

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() :

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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