[英]Python: how can I count the occurrences in a list of tuples?
I have a list
of tuples
, with each tuple having two elements: an integer and an inner list. 我有一个
tuples
list
,每个元组都有两个元素:一个整数和一个内部列表。 The list of tuples has len=900
and each inner list can have len=2
, len=3
, or len=4
depending on the case being. 元组列表具有
len=900
,每个内部列表可以具有len=2
, len=3
或len=4
视情况而定)。
This is an excerpt of the list: 这是列表的摘录:
mylist=[(0, [1.0, 1.0]), (1, [1.0, 1.0, 1.0]), ..., (31, [1.0, 1.0, 1.0, 1.0]), ...]
. mylist=[(0, [1.0, 1.0]), (1, [1.0, 1.0, 1.0]), ..., (31, [1.0, 1.0, 1.0, 1.0]), ...]
This is a specific case in which each element of the inner lists is 1.0
, but I want to deal with the generic case featuring different values. 这是内部列表的每个元素都是
1.0
的特定情况,但是我想处理具有不同值的通用情况。
My questions: 我的问题:
1) How can I count the total number of elements within the inner lists? 1)如何计算内部列表中的元素总数? In the visualized example this number would be
2+3+4=9
. 在可视化的示例中,该数字将为
2+3+4=9
。
2) How can I count the occurrences of each value (or, better, of each bin ) within the inner lists? 2)如何计算内部列表中每个值(或更佳的是每个bin )的出现次数?
Here's something to get you started. 这是一些可以帮助您入门的东西。 For #1, you can get the lengths of each part of the tuples with a list comprehension:
对于#1,您可以通过列表理解来获取元组各部分的长度:
lens = [len(y) for x, y in mylist]
This will generate an array of the lengths of each sublist in the tuples, so lens[0]
will equal 2, etc. 这将生成一个元组中每个子列表的长度的数组,因此
lens[0]
等于2,依此类推。
You just iterate through the list then iterate through the inner list and you create a dictionnary to count each value separately. 您只需要遍历列表,然后遍历内部列表,就可以创建字典来分别计算每个值。 Also you increment for each innerlist a variable to count the elements.
同样,您为每个内部列表增加一个变量以计算元素。
inner_list_count = 0
value_count = dict()
for key,innerlist in mylist:
inner_list_count += len(innerlist)
for value in innerlist:
if value not in value_count:
value_count(value) = 0
value_count(value) += 1
Number of elements: 元素数:
sum(len(l) for _, l in mylist)
Number of occurrences: 出现次数:
from collections import Counter
Counter(x for _, l in mylist for x in l)
Occurrences binned: 分类的发生次数:
from collections import Counter
binsize = 100
Counter(x - x % binsize for _, l in mylist for x in l)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.