我只是 python 的初学者,我想知道是否可以从列表中删除所有整数值?例如文档是这样的
['1','introduction','to','molecular','8','the','learning','module','5']
删除后我希望文档看起来像:
['introduction','to','molecular','the','learning','module']
最佳答案
要删除所有整数,请执行以下操作:
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)
关于python - 如何从python中的列表中删除所有整数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3159155/