仅循环循环3次。为什么呢?

时间:2018-02-09 14:55:09

标签: python python-3.x

我写了一个看似简单的循环。列表中有6个项目,它应该循环六次。但是,它只循环3次。的为什么吗

list1 = 'one two three four five six'
newlist = list1.split(' ')
print (newlist)
list2 = ['seven', 'eight', 'nine', 'ten', 'eleven', 'twelve']

for number in list2:
    nextnumber = list2.pop()
    print ("Adding number ", nextnumber)
    newlist.append(nextnumber)

print (newlist)

6 个答案:

答案 0 :(得分:1)

如评论中所述,您在迭代时删除项目。您可以使用while循环更好地建模此模式:

while list2:
    newlist.append(list2.pop())

答案 1 :(得分:1)

使用list2循环将newlist添加到for可以这样做:

for number in list2:
    print ("Adding number ", number)
    newlist.append(number)

但短暂,快速和pythonic的方式是

newlist.extend(list2)

答案 2 :(得分:1)

请改用以下代码:

for number in list2:
    print ("Adding number ", number)
    newlist.append(number)
print (newlist)

观察:list2.pop()正在减少你的列表元素,它也减少了循环次数

答案 3 :(得分:0)

它只会循环三次,因为您正在主动修改list2。一个简单的修正就是复制!!

导入副本

list2_c = copy.copy(list2)

for num in list2_c:
.
.
.
.

答案 4 :(得分:0)

快速回答,复制list2:

list1 = 'one two three four five six'
newlist = list1.split(' ')
print (newlist)
list2 = ['seven', 'eight', 'nine', 'ten', 'eleven', 'twelve']

for number in list(list2):
    nextnumber = list2.pop()
    print ("Adding number ", nextnumber)
    newlist.append(nextnumber)

print (newlist)

答案 5 :(得分:0)

像先前的答案所说的那样,你正在使用list2,换句话说,当你为list2中的数字做时,你正在服用7,8,9但从​​不使用它们,而是你要删除12,11,10从列表中打印出来。你可以这样做:

    for number in list2:
    #Unless you want to append in reverse order(see below for that)
    #comment the next line
        #nextnumber = list2.pop() 
        print ("Adding number ", number) 
        newlist.append(number)#Append the number you just got from list2
    print (newlist)

  out[:]: ['one', 'two', 'three', 'four', 'five', 'six']
  Adding number  seven
  Adding number  eight
  Adding number  nine
  Adding number  ten
  Adding number  eleven
  Adding number  twelve
  ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 
  'ten', 'eleven', 'twelve']

如果您想以相反的顺序追加,请执行@thachnb建议的内容。