简体   繁体   English

python reduce:查找元组列表中所有列表的总大小

[英]python reduce: find total size of all lists inside list of tuples

my data structure looks as below 我的数据结构如下所示

itemsData = [('data1', [1, 2, 3, 4]), ('data2', [1, 2]), ('data3', [1, 2, 3])]

I want to find total number of items in the list of tuples above. 我想在上面的元组列表中找到项目总数。 For above example, len([1,2,3,4] + len([1,2]) + len([1,2,3]) = 9 对于上面的例子,len([1,2,3,4] + len([1,2])+ len([1,2,3])= 9

reduce(lambda x,y: len(x[1]) + len(y[1]), itemsData )

error i get is 我得到的错误是

TypeError: 'int' object has no attribute '__getitem__'

You could simply try: 你可以试试:

sum([len(elem[1]) for elem in itemsData])

Eg 例如

>>> itemsData = [('data1', [1, 2, 3, 4]), ('data2', [1, 2]), ('data3', [1, 2, 3])]
>>> sum([len(elem[1]) for elem in itemsData])
9

I will explain why your code does not work 我将解释为什么你的代码不起作用

from https://docs.python.org/2/library/functions.html#reduce , 来自https://docs.python.org/2/library/functions.html#reduce

The left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable 左参数x是累加值,右参数y是迭代的更新值

So in the first iteration, your code len(x[1]) + len(y[1]) works since x=('data1', [1, 2, 3, 4]) , y=('data2', [1, 2]) , and the result is 6 , 所以在第一次迭代中,你的代码len(x[1]) + len(y[1])起作用,因为x=('data1', [1, 2, 3, 4])y=('data2', [1, 2]) ,结果是6

However in the second iteration, you get x=6 , y=('data3', [1, 2, 3])] , so len(x[1]) is invalid. 但是在第二次迭代中,得到x=6y=('data3', [1, 2, 3])] ,因此len(x[1])无效。

The correct code using reduce, is 使用reduce的正确代码是

reduce(lambda x,y: x+len(y[1]), itemsData, 0)

This works since 这是有效的

1st iteration ... x = 0, y = ('data1', [1, 2, 3, 4]), result = 4
2nd iteration ... x = 4, y = ('data2', [1, 2]), result = 6
3rd iteration ... x = 6, y = ('data3', [1, 2, 3]), result = 9

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

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