给出一个清单
[1,2,3,4,5,6]
使用2n
元素
如何获取列表
[1+2,3+4,5+6]
有n
个元素吗?
答案 0 :(得分:2)
def grouper(n, iterable, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
然后致电:
for paired in grouper(2, inputlist):
# paired is a tuple of two elements from the inputlist at a time.
grouper
返回一个迭代器;如果您拥有以获得列表,只需将iterable消费到新列表中:
newlist = list(grouper(2, inputlist))
答案 1 :(得分:2)
a = [1,2,3,4,5,6]
b = [a[i]+a[i+1] for i in xrange(0,len(a),2)]
答案 2 :(得分:2)
li = [1,2,10,20,100,200,2000,3000,2,2,3,3,5,5]
print li
it = iter(li)
if len(li)%2==0:
print [x+it.next() for x in it]
给出
[1, 2, 10, 20, 100, 200, 2000, 3000, 2, 2, 3, 3, 5, 5]
[3, 30, 300, 5000, 4, 6, 10]