【发布时间】:2021-03-15 22:37:39
【问题描述】:
我的学校作业要求我从用户那里读取一个列表,然后从中删除所有奇怪的元素。我用来检查奇数的循环甚至不会遍历所有列表元素。
ans=1
lst=[]
while ans!=0:
no=int(input('Enter value for list or press 0 to exit:'))
if no!=0:
lst.append(no)
else:
break
print('\nYour list is:',lst)
for i in lst: # loop to check for odd nos
print('i is', i)
if i%2==1:
lst.remove(i)
print('List after removing odd elements:',lst)
在第二个循环中,我添加了 print 语句来检查不一致的输出,结果如下: Output
某些列表元素在迭代时被跳过(?),因此它们没有被删除,这给了我不正确的输出。为什么会发生这种情况?
【问题讨论】:
-
如果在迭代列表的同时从列表中删除元素,您将获得有趣的结果。这个问题有一些很好的答案可以更好地解释它stackoverflow.com/questions/6260089/…
标签: python python-3.x list for-loop