删除列表中的非 int 元素



嗨,我在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) 

试试这个:

>>> messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]
>>> [elem for elem in messy_list if type(elem) == int]
[2, 3, 1]

该问题与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] ,这是您想要的。

最新更新