【问题标题】:Appending List Items and Printing the Entire List附加列表项并打印整个列表
【发布时间】:2013-07-25 10:24:02
【问题描述】:

我已经简化了我正在处理的代码,以确定问题所在。我查看了其他问题、教科书和 python.org,但缺少一些基本概念。

def array_():

  i=0
  while i <2:
    item= "a"+ str(i)
    List=[]
    List.append(item)
    print "item index is ", i, "item is ", item
    i+=1
  print List

print "item index is ", i, "item is ", item

对于打印列表,我得到了输出:

[a1] 

我正在尝试打印整个列表。

我做错了什么,是没有将项目添加到列表中,还是我错误地要求查看整个列表?

请不要判断,我有时很难掌握最简单的东西。

【问题讨论】:

  • 值得注意的是,您应该避免使用CapWords 作为变量名——使用lowercase_with_underscoresPEP-8 建议 CapWords 留作上课。
  • 为什么List=[]在while循环里面?它在连续迭代中重新创建列表

标签: python list append jython


【解决方案1】:

您正在循环中的每次迭代创建一个新列表。将List=[] 移出循环。

List=[]
while i <2:
    item= "a"+ str(i)
    List.append(item)
    print "item index is ", i, "item is ", item
    i+=1

【讨论】:

    【解决方案2】:

    您也可以考虑使用列表推导来避免这些问题,例如

    my_list = ["a"+str(i) for i in range(2)] # xrange() for longer lists
    print my_list # ['a0', 'a1']
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多