删除lis中的not int元素

2024-04-23 08:42:57 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: andofthe代码in元素istype
2条回答

试试这个:

>>> 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],这是您想要的。你知道吗

相关问题 更多 >