简体   繁体   English

Python计算元组列表中元素的方法

[英]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? 使用元组的第一个元素作为输出列表的索引来创建每个元组的第一个元素的计数列表的Python方法是什么? So the tuple (0, 0.2202) would increment the counter for element 0 of the output list. 因此,元组(0, 0.2202)将增加输出列表中元素0的计数器。 For this example, the result would be [2, 1, 1, 0, 1, 0, 1, 0, 0, 0, 2] . 对于此示例,结果将为[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. 请注意,如示例中所示,它假定每个元组的第一个元素的最大值为10。

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. 它包含一个用于处理嵌套列表的双生成器表达式,因此可以说它是Pythonic是有争议的,但是我喜欢它的简洁性。 You can use itertools.chain or itertools.chain.from_iterable if you prefer to keep the number of nested for-loops down. 如果您希望减少嵌套的for循环数,则可以使用itertools.chainitertools.chain.from_iterable

If you want to know what is the max value to put on the range call : 如果您想知道要进行range调用的最大值是多少:

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

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

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