[英]Python adding elements of a list together to get a new list
lets say I have a list:假设我有一个清单:
list1 = [1,2,3,4,5,6,7,8]
I want to add the elements of the list to create a new list like so:我想添加列表的元素来创建一个新列表,如下所示:
newlist = [(1+2),(3+4),(5+6),(7+8)]
Using an iterator使用迭代器
s = iter(list1)
list(map(sum, zip(s,s)))
[3, 7, 11, 15]
使用 zip 和列表切片:
[x+y for x, y in zip(list1[::2], list1[1::2])]
With an array like this像这样的数组
list = [1,2,3,4,5,6,7,8]
The easiest to understand code would be something like this最容易理解的代码是这样的
new_list = []
for index in range(0,len(list),2):
sum = list[index] + list[index+1]
new_list.append(sum)
Of course, that is a bit length.当然,这有点长。 We can do the same thing using list comprehension.我们可以使用列表理解来做同样的事情。
list = [list[index] + list[index+1] for index in range(0,len(list),2)]
or another option:或其他选择:
list = [x+y for x, y in zip(list[::2], list[1::2])]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.