【问题标题】:Python operation data List in loopPython操作数据List in loop
【发布时间】:2016-12-20 09:04:26
【问题描述】:

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

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]

我该如何解决这个问题?

【问题讨论】:

  • 进一步了解range 命令的作用。您已经接近了,但是您正在根据 a 修改范围的错误部分。
  • 干草伊多斯。我的操作数据列表有问题,我无法将列表 1 与列表 2 相加。你能给我解决方案吗??

标签: python list loops sum conditional-statements


【解决方案1】:

基于您现有的代码,我将使用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]

【讨论】:

  • Hay Idos.. 非常感谢...但我不能使用外部代码。
【解决方案2】:

你可以使用地图

result = []
while True:
    a = input('Input : ')
    n = range(1, a+1)
    result = [(x or 0) + (y or 0) for x,y in map(None, n, result)]
    print result

结果是:

Input : 3
[1, 2, 3]
Input : 2
[2, 4, 3]
Input : 6
[3, 6, 6, 4, 5, 6]

【讨论】:

  • hai.. Taxellool .. 感谢您的回答,但我无法用您的回答解决我的问题
  • 为什么?你有什么问题?
  • Traceback(最近一次调用最后一次):文件“haha.py”,第 4 行,在 结果 = [(x 或 0)+(y 或 0)对于地图中的 x,y (None, n, result)] NameError: name 'result' is not defined
  • 定义好了..看第一行result = []
  • 您忘记添加第一行。你没有定义结果。如答案所示,在循环之前添加“result = []”,它可以工作。
【解决方案3】:

但我不能使用外部代码

然后,您可以编写一些代码,当新条目比之前的结果更长时,它的作用与izip_longest 的零填充完全一样。

总和在列表推导中执行,其中输入列表中的值和索引是通过在推导中的条目上应用enumerate 来获取的。累积列表中的值被索引并添加到​​同一索引处的新值:

tot = []
while True:
    a = input('Input : ')
    n = range (1,a+1,1)
    x, y = len(tot), len(n)
    if y > x:
        tot[x:y] = [0]*(y-x) # pad the tot list with zeros
    tot[:y] = [tot[i]+v for i, v in enumerate(n)]
    print tot

输出:

Input : 3
[1, 2, 3]
Input : 2
[2, 4, 3]
Input : 6
[3, 6, 6, 4, 5, 6]
Input : 1
[4, 6, 6, 4, 5, 6]
Input : 0
[4, 6, 6, 4, 5, 6] 

【讨论】:

  • 你的答案是可行的,但我不明白这段代码 [tot[i]+v for i, v in enumerate(n)]
  • 你能告诉我吗
猜你喜欢
  • 2022-12-02
  • 2022-12-26
  • 2023-02-06
  • 2018-11-08
  • 2016-03-21
  • 2022-11-20
  • 2019-04-04
  • 1970-01-01
  • 2016-12-16
相关资源
最近更新 更多