本文介绍了如何从python中的列表中删除所有整数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只是 Python 的初学者,我想知道是否可以从列表中删除所有整数值?例如文档如下
I am just a beginner in python and I want to know is it possible to remove all the integer values from a list? For example the document goes like
['1','introduction','to','molecular','8','the','learning','module','5']
删除后我希望文档看起来像:
After the removal I want the document to look like:
['introduction','to','molecular','the','learning','module']
推荐答案
要删除所有整数,请执行以下操作:
To remove all integers, do this:
no_integers = [x for x in mylist if not isinstance(x, int)]
但是,您的示例列表实际上并不包含整数.它仅包含字符串,其中一些仅由数字组成.要过滤掉它们,请执行以下操作:
However, your example list does not actually contain integers. It contains only strings, some of which are composed only of digits. To filter those out, do the following:
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)
这篇关于如何从python中的列表中删除所有整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!