首页 > 解决方案 > Remove not int elements in list

问题描述

Hi I have this task in python and I should remove all not int elements, the result of the code down below is [2, 3, 1, [1, 2, 3]] and I have no idea why in the result the list is not moved away. Only tested suggestions please, I mean working ones.

# 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) 

标签: python

解决方案


试试这个:

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

推荐阅读