如何在Python中从列表中移除所有整数值
我刚开始学习Python,想知道有没有办法从一个列表中去掉所有的整数值?比如说,原来的列表是这样的:
['1','introduction','to','molecular','8','the','learning','module','5']
去掉整数之后,我希望列表变成这样:
['introduction','to','molecular','the','learning','module']
8 个回答
13
你也可以这样做:
def int_filter( someList ):
for v in someList:
try:
int(v)
continue # Skip these
except ValueError:
yield v # Keep these
list( int_filter( items ))
为什么呢?因为用 int
这种方式比试着写一些规则或者正则表达式来识别字符串值(那些表示整数的字符串)要简单得多。
14
你列表里的所有项目都不是整数。它们其实是只包含数字的字符串。所以你可以使用 isdigit
这个字符串方法来筛选出这些项目。
items = ['1','introduction','to','molecular','8','the','learning','module','5']
new_items = [item for item in items if not item.isdigit()]
print new_items
文档链接:http://docs.python.org/library/stdtypes.html#str.isdigit
42
要去掉所有的整数,可以这样做:
no_integers = [x for x in mylist if not isinstance(x, int)]
不过,你的例子列表其实并不包含整数。它里面只有字符串,其中一些字符串只是由数字组成。要把这些字符串过滤掉,可以这样做:
no_integers = [x for x in mylist if not (x.isdigit()
or x[0] == '-' and x[1:].isdigit())]
另外一种方法是:
is_integer = lambda s: s.isdigit() or (s[0] == '-' and s[1:].isdigit())
no_integers = filter(is_integer, mylist)