用 pop()方法遍历列表演示 Python while 语句执行过程

释放双眼,带上耳机,听听看~!
numbers = [12,37,5,42,8,3]
even = []
odd = []
print "numbers" ,numbers
while len(numbers)>0:
    number = numbers.pop()
    if number % 2 == 0:
        even.append(number)
    else:
        odd.append(number)
    print "numbers" ,numbers
    print "even",even
    print  "odd",odd

运行结果

numbers [12, 37, 5, 42, 8, 3]
numbers [12, 37, 5, 42, 8]
even []
odd [3]
numbers [12, 37, 5, 42]
even [8]
odd [3]
numbers [12, 37, 5]
even [8, 42]
odd [3]
numbers [12, 37]
even [8, 42]
odd [3, 5]
numbers [12]
even [8, 42]
odd [3, 5, 37]
numbers []
even [8, 42, 12]
odd [3, 5, 37]

分别将奇数偶数放到新的列表中。
同时注意一点如果把print 语句提到while同列的位置,就是输出最终的结果,而不是过程了。
用 pop()方法遍历列表演示 Python while 语句执行过程

【转自慕课】https://www.imooc.com

Python

python 多继承使用基础

2022-3-3 13:26:41

Python

Django rest framework实现token登陆、修改

2022-3-3 13:29:31

搜索