Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 删除列表中的not int元素_Python - Fatal编程技术网

Python 删除列表中的not int元素

Python 删除列表中的not int元素,python,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 sho

您好,我在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 = ["a", 2, 3, 1, False, [1, 2, 3]]
>>> [elem for elem in messy_list if type(elem) == int]
[2, 3, 1]
试试这个:

>>> 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=[“a”,2,3,1,False,“a”]
您将得到
[2,3,1,“a”]

另一方面:
[type(elem)==int时凌乱列表中元素的元素]

返回所需的
[2,3,1]

问题与
凌乱列表中是否存在列表无关,而是与您在对列表进行迭代时正在修改列表这一事实有关

例如,使用
messy_list=[“a”,2,3,1,False,“a”]
您将得到
[2,3,1,“a”]

另一方面:
[type(elem)==int时凌乱列表中元素的元素]

返回所需的
[2,3,1]

是否删除列表?或者,不要修改正在迭代的列表。您在迭代列表时正在修改列表。这种行为没有定义。特别是,在这种情况下,它似乎删除了
False
,因此将列表移动到
False
的旧位置,然后发现下一个索引超出了列表的范围。您应该创建一个新的列表,或者实际上,使用列表理解。@MeesdeVries行为是定义的和一致的,它只是不直观,所以不是recommended@Chris_rands,我的错,谢谢你的更正。你想删除列表吗?或者,不要修改正在迭代的列表。您在迭代列表时正在修改列表。这种行为没有定义。特别是,在这种情况下,它似乎删除了
False
,因此将列表移动到
False
的旧位置,然后发现下一个索引超出了列表的范围。您应该创建一个新的列表,或者实际上,使用列表理解。@MeesdeVries行为是定义的和一致的,它只是不直观,所以不是recommended@Chris_rands,我的错,谢谢你的更正。
type(1)
只是
int
@Chris\u Rands这不是OP想要的吗?标题说-不要从列表中删除int元素我认为如果type(elem)是int,那么
在这种情况下可能会更好是的,但是为什么每次都要调用
type(1)
,而你知道类型是
int
?只需使用
type(elem)==int
type(1)
就是
int
@Chris\u Rands这不是OP想要的吗?标题说-不要从列表中删除int元素我认为如果type(elem)是int,那么
在这种情况下可能会更好是的,但是为什么每次都要调用
type(1)
,而你知道类型是
int
?只需使用
type(elem)==int