[英]Python error with flattening list of lists
Hi I'm trying to flatten the following list of lists but I always get the following error: 嗨,我正在尝试展平以下列表,但始终会出现以下错误:
'int' object is not iterable 'int'对象不可迭代
I also tried chain from itertools but still not working. 我还尝试了itertools的链,但仍然无法正常工作。 I guess the solution is easy but I really cannot see it!
我想解决方案很简单,但我真的看不到! Anybody can help?
有人可以帮忙吗?
Thanks 谢谢
from itertools import chain
import operator
lista = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
listone = lista[0][0],[-x[0] for x in lista[:2]]
#sumlistone = chain.from_iterable(listone)
sumlistone = [x for sublist in listone for x in sublist]
print listone
print sumlistone
Is this what you need? 这是您需要的吗?
lista = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
listb = []
for sub in lista:
listb.extend(sub) # Modification suggested by @Dinesh Pundkar
print(listb)
print(sum(listb))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.