Python循环中操作数据List

标签 python list loops sum conditional-statements

我想解决我的编程问题,问题是这样的:

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/

相关文章:

python - 使用Dlib/python检测额头点

python - 将文件解密为流并将流读入 p​​andas(hdf 或 stata)

c - 汇编程序中的循环迭代不正确

python - 多处理调试技术

c# - 如何使用 foreach 获取 List 对象属性值的总和

r - 提取元素名称相似的嵌套列表元素

sql-server-2008 - sql server 2008 中的程序集列表

java - 安卓 Java : Can't figure out how to loop my VideoView

循环内的 JavaScript 闭包 – 简单的实际示例

python - PANDAS:需要帮助计算列中存在的项目列表的实例,以及对匹配的另一列中的值求和