我想按升序将每个元素从一个列表转移到另一个列表.这是我的代码:
l=[10,1,2,3,4,5,6,7,8,9]
p=[]
for x in l :
p.append(min(l))
l.remove(min(l))
print p
print l
Run Code Online (Sandbox Code Playgroud)
但它返回此结果:
[1, 2, 3, 4, 5]
[10, 6, 7, 8, 9]
Run Code Online (Sandbox Code Playgroud)
我不知道为什么它停在中途,请帮帮我...谢谢!
这样做:
p = sorted(l)
#l = [] if you /really/ want it to be empty after the operation
Run Code Online (Sandbox Code Playgroud)
你变得不稳定的原因是你在l 迭代它时改变了序列的大小,导致你跳过元素.
如果你想修复你的方法,你会这样做:
for x in l[:]:
Run Code Online (Sandbox Code Playgroud)
l[:]创建一个复制的l,它,而你做的事情原来你可以放心地迭代l.