python reduce:查找元组列表中所有列表的总大小
python reduce: find total size of all lists inside list of tuples
我的数据结构如下所示
itemsData = [('data1', [1, 2, 3, 4]), ('data2', [1, 2]), ('data3', [1, 2, 3])]
我想在上面的元组列表中找到项目的总数。对于上面的例子,len([1,2,3,4] + len([1,2]) + len([1,2,3]) = 9
reduce(lambda x,y: len(x[1]) + len(y[1]), itemsData )
我得到的错误是
TypeError: 'int' object has no attribute '__getitem__'
您可以简单地尝试:
sum([len(elem[1]) for elem in itemsData])
例如
>>> itemsData = [('data1', [1, 2, 3, 4]), ('data2', [1, 2]), ('data3', [1, 2, 3])]
>>> sum([len(elem[1]) for elem in itemsData])
9
我会解释为什么你的代码不起作用
来自 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
所以在第一次迭代中,你的代码
len(x[1]) + len(y[1])
从 x=('data1', [1, 2, 3, 4])
、y=('data2', [1, 2])
起起作用,结果是 6
、
但是在第二次迭代中,您得到 x=6
、y=('data3', [1, 2, 3])]
、
所以 len(x[1])
无效。
使用 reduce 的正确代码是
reduce(lambda x,y: x+len(y[1]), itemsData, 0)
自
起有效
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
我的数据结构如下所示
itemsData = [('data1', [1, 2, 3, 4]), ('data2', [1, 2]), ('data3', [1, 2, 3])]
我想在上面的元组列表中找到项目的总数。对于上面的例子,len([1,2,3,4] + len([1,2]) + len([1,2,3]) = 9
reduce(lambda x,y: len(x[1]) + len(y[1]), itemsData )
我得到的错误是
TypeError: 'int' object has no attribute '__getitem__'
您可以简单地尝试:
sum([len(elem[1]) for elem in itemsData])
例如
>>> itemsData = [('data1', [1, 2, 3, 4]), ('data2', [1, 2]), ('data3', [1, 2, 3])]
>>> sum([len(elem[1]) for elem in itemsData])
9
我会解释为什么你的代码不起作用
来自 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
所以在第一次迭代中,你的代码
len(x[1]) + len(y[1])
从 x=('data1', [1, 2, 3, 4])
、y=('data2', [1, 2])
起起作用,结果是 6
、
但是在第二次迭代中,您得到 x=6
、y=('data3', [1, 2, 3])]
、
所以 len(x[1])
无效。
使用 reduce 的正确代码是
reduce(lambda x,y: x+len(y[1]), itemsData, 0)
自
起有效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