我想解决我的编程问题,问题是这样的:
input: 3 #if i input as first input example 3, output is [1, 2, 3]
[1, 2, 3]
input: 2 #2nd input example 2 output is [1, 2] + [1, 2, 3] = [2, 4, 6]
[2, 4, 3]
input: 6 #3rd input [2, 4, 6] + [1, 2, 3, 4, 5, 6] = [3, 6, 6, 4, 5, 6]
[3, 6, 6, 4, 5, 6]
我的代码:
while True:
a = input('Input : ')
n = range (1,a+1,1)
print n
输出:
Input : 3
[1, 2, 3]
Input : 2
[1, 2]
Input : 6
[1, 2, 3, 4, 5, 6]
如何解决这个问题?
最佳答案
基于您现有的代码,我将使用 itertools.izip_longest
(Python 2,对于 3 使用 zip.longest
):
>>> import itertools
>>> nxt = []
>>> while True:
a = input('Input : ')
n = range(1, a+1, 1) # could change to range(1, a+1)
nxt = map(sum, itertools.izip_longest(n, nxt, fillvalue=0))
print nxt
其产量:
Input : 3
[1, 2, 3]
Input : 2
[2, 4, 3]
Input : 6
[3, 6, 6, 4, 5, 6]
关于Python循环中操作数据List,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38933384/