首页 > 解决方案 > I want to remove all strings from a list of integers. Why doesn't this work?

问题描述

When I run this code, it works, but for some reason it only removes the 'p' and 'h' strings and not the 'z' string. Why?

def filter_list(l):
    for item in l:
        if item == str(item):
            l.remove(item)
    return l
print(filter_list([1, 9, 3, 'p', 'z', 7, 'h']))

output:[1, 9, 3, 'z', 7]

标签: pythonstringlistinteger

解决方案


能做:

def filter_list(l):    
    return [i for i in l if type(i) is not str]

输出:

>>> filter_list(['e', 'f', 1, 'c', 2, 4])
[1, 2, 4]

l[i]检查是否不是字符串后仅返回整数


推荐阅读