如何使用filter()从包含字符串和数字的列表中删除所有字符串?

Age*_*t π 2 python list filter

我有一个列表例如

list = [1,2,3,'t',4,5,'fgt',6,7,'string']
Run Code Online (Sandbox Code Playgroud)

我想使用该filter()函数删除所有字符串只留下数字.我可以用常规方法做到这一点,但我不能用过滤方法做任何提示?

所以:

list(filter(type(i)==str,a)))
Run Code Online (Sandbox Code Playgroud)

不会工作...我试图使用它,但仍然不起作用:

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    list(filter(type(a[-1])==str,a))
TypeError: 'bool' object is not callable
Run Code Online (Sandbox Code Playgroud)

Sha*_*ger 7

虽然你可以使用filter它,但不要.你需要一个lambda函数来做它,它比同等的列表理解或生成器表达式更慢,更不易读.相反,只需使用listcomp或genexpr:

old_list = [1,2,3,'t',4,5,'fgt',6,7,'string']
new_list = [x for x in old_list if isinstance(x, (int, float))]
# or to remove str specifically, rather than preserve numeric:
new_list = [x for x in old_list if not isinstance(x, str)]
Run Code Online (Sandbox Code Playgroud)

这比filter+ lambda等价物要简单得多:

new_list = list(filter(lambda x: isinstance(x, (int, float)), old_list))
Run Code Online (Sandbox Code Playgroud)

正如指出的COLDSPEED的回答,一般可以接受所有"号相似者",你应该实际使用的isinstancenumbers.Number; 使用(int, float)手柄字面类型,但不会处理complex,fractions.Fraction,decimal.Decimal,或第三方的数字类型.