【发布时间】:2018-04-30 23:54:48
【问题描述】:
嗨,我在 python 中有这个任务,我应该删除所有非 int 元素,下面代码的结果是[2, 3, 1, [1, 2, 3]],我不知道为什么结果列表没有被移走。请仅提供经过测试的建议,我的意思是可行的建议。
# Great! Now use .remove() and/or del to remove the string,
# the boolean, and the list from inside of messy_list.
# When you're done, messy_list should have only integers in it
messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]
for ele in messy_list:
print('the type of {} is {} '.format(ele,type(ele)))
if type(ele) is not int:
messy_list.remove(ele)
print(messy_list)
【问题讨论】:
-
要删除列表吗?或扁平化
-
不要修改你正在迭代的列表。
-
您在迭代列表时正在修改列表。这种行为是未定义的。特别是在这种情况下,它似乎删除了
False,因此将列表移动到False的旧位置,然后发现下一个索引超出了列表的范围。您应该创建一个新列表,或者实际上使用列表推导式。 -
@MeesdeVries 行为已定义且一致,只是不直观,因此不推荐
-
@Chris_rands,我的错,谢谢你的纠正。
标签: python