【问题标题】:How to append list of all results from a For loop?如何附加 For 循环中所有结果的列表?
【发布时间】:2014-10-24 16:39:37
【问题描述】:

我正在努力让我的功能正常工作。这是它的基础:

#for example:
data=[(b),(c),(d),(e)]

results=[]
for x in data: #this goes through each row of the data
    # body_code executes. This part is mostly just changing types, etc
    a=final_body_code
    results.append(a)
print results

#output should be: results=[(b),(c),(d),(e)] #After changing types of b,c,d,e etc.

#The body of the code does not matter at this point, it's just the appending which i'm
#struggling with. 

但是,当我这样做时,它似乎没有将 a 附加到结果列表中。我是python的新手,所以请帮忙!

【问题讨论】:

  • 为我们提供输入/预期输出?
  • 首先,-> 是什么?这应该是评论吗?其次,你确定data 不是空的还是None?第三,你的意思是它通过每一行?还有更多问题......提供更多细节。
  • print out data 并确保这些不是空的(又名None)。 data 是嵌套列表吗?
  • 给我们一个minimal runnable example that demonstrates the problem when you run it。您的问题没有包含足够的信息来诊断问题。
  • 确保到达内部 for 循环。在循环中放置一个打印语句。如果data 为空,则结果将为空,因为将跳过循环

标签: python list loops printing append


【解决方案1】:

我认为这是你愿意做的。

data=[(b),(c),(d),(e)]

results=[]

for x in data:
    results.append(x)

print results

【讨论】:

    【解决方案2】:

    您应该添加示例。

    也许你在a=final_body_code 有问题,结果是None

    但是,使用list comprehension 对@Mrinal Wahal 的回答进行了一点改进:

    results = [final_body_code(i) for i in data]
    

    【讨论】:

      【解决方案3】:
      data = [b, c, d, e]
      
      results = []
      
      results.extend(final_body_code(i) for i in data)
      
      return results
      

      【讨论】:

        猜你喜欢
        • 2012-08-02
        • 1970-01-01
        • 2019-07-12
        • 1970-01-01
        • 2020-03-26
        • 1970-01-01
        • 2013-01-06
        • 2015-04-27
        • 2016-07-24
        相关资源
        最近更新 更多