【问题标题】:for loop not iterating through all list elements in pythonfor循环没有遍历python中的所有列表元素
【发布时间】:2018-08-07 10:15:00
【问题描述】:
things="pen pencil apple mango litchi grapes pear song music"
stuff=things.split(" ")
items=["a","b","c","d"]

for word in items:
    next_one=items.pop()
    stuff.append(next_one)
print(stuff)

当我运行此代码时,结果列表显示只有最后两个元素是从项目中附加的。为什么不附加所有元素?

【问题讨论】:

  • stuff.append(word)删除next_one=items.pop()

标签: python-3.x list for-loop


【解决方案1】:

因此,您修改项目引用您只会添加两个元素。 您可以在下面看到循环每一步中 items 变量中的所有值。

第 1 步

项目 = ["a","b","c","d"] next_one = 'd'

第 2 步

项目 = ["a","b","c"] next_one = 'c'

第三步

项目 = ["a","b"] 循环到此结束

要解决它,你可以改变

for word in items:

while(items):

或者你可以写成一行:

stuff.extend(list(reversed(items)))

【讨论】:

  • 为什么项目列表只有“a”和“b”时循环结束?
  • 在这里你会找到答案quora.com/…
猜你喜欢
  • 1970-01-01
  • 2015-07-24
  • 1970-01-01
  • 2021-07-14
  • 2017-01-25
  • 1970-01-01
  • 2017-02-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多