简体   繁体   中英

Python approach to counting elements in a list of a list of tuples

Given a list of a list of tuples like

test = [[(2, 0.66835654), (0, 0.22021745), (1, 0.060669053), (6, 0.047858406)],
        [(10, 0.6511003), (0, 0.3458588)],
        [(4, 0.9961432)],
        [(10, 0.9917404)]]

What is the Pythonic way to create a list of counts of the first element of each tuple, using the first element of the tuple as the output list's index? So the tuple (0, 0.2202) would increment the counter for element 0 of the output list. For this example, the result would be [2, 1, 1, 0, 1, 0, 1, 0, 0, 0, 2] .

If I understand the question correctly, there's an error in your listed expected output. See if this gives you what you're looking for. Note that it assumes the max of the first element of each tuple is 10 as in the example.

test = [[(2, 0.66835654), (0, 0.22021745), (1, 0.060669053), (6, 0.047858406)],
        [(10, 0.6511003), (0, 0.3458588)],
        [(4, 0.9961432)],
        [(10, 0.9917404)]]

results = [0 for _ in range(11)]

for row in test:
    for element in row:
        results[element[0]] = results[element[0]] + 1
> print(results)
> [2, 1, 1, 0, 1, 0, 1, 0, 0, 0, 2]
from collections import Counter
counter = Counter(item[0] for sublist in test for item in sublist)
results = [counter[i] for i in range(11)]

This contains a double generator expression to deal with the nested lists, so it's arguable how Pythonic it is, but I like how succinct it is. You can use itertools.chain or itertools.chain.from_iterable if you prefer to keep the number of nested for-loops down.

If you want to know what is the max value to put on the range call :

from operator import itemgetter
max_value = max(map(itemgetter(0), sum(test, [])))

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