嗨,我在python中有这个任务,我应该删除所有not 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)
试试这个:
这个问题与您的
messy_list
中是否存在列表无关,而是与您在遍历列表时正在修改列表这一事实有关。你知道吗例如,使用
messy_list = ["a", 2, 3, 1, False, "a"]
可以得到[2, 3, 1, "a"]
。你知道吗另一方面:
[elem for elem in messy_list if type(elem) == int]
返回[2, 3, 1]
,这是您想要的。你知道吗相关问题 更多 >
编程相关推荐