【发布时间】:2011-03-10 16:54:58
【问题描述】:
我只是 python 的初学者,我想知道是否可以从列表中删除所有整数值?例如文档是这样的
['1','introduction','to','molecular','8','the','learning','module','5']
删除后我希望文档看起来像:
['introduction','to','molecular','the','learning','module']
【问题讨论】:
我只是 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)
【讨论】:
你也可以这样做:
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 比尝试编写规则或正则表达式来识别编码整数的字符串值要好。
【讨论】:
int 比str.isdigit 更好?
'-2'.isdigit() 将返回False。
float,但仍然同样相关)。
列表中的所有项目都不是整数。它们是只包含数字的字符串。所以你可以使用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
【讨论】:
我个人喜欢过滤器。我认为如果以明智的方式使用它可以帮助保持代码的可读性和概念上的简单:
x = ['1','introduction','to','molecular','8','the','learning','module','5']
x = filter(lambda i: not str.isdigit(i), x)
或
from itertools import ifilterfalse
x = ifilterfalse(str.isdigit, x)
注意第二个返回一个迭代器。
【讨论】:
请不要使用这种方式从列表中删除项目:(由 THC4k 评论后编辑)
>>> li = ['1','introduction','to','molecular','8','the','learning','module','5']
>>> for item in li:
if item.isdigit():
li.remove(item)
>>> print li
['introduction', 'to', 'molecular', 'the', 'learning', 'module']
这不起作用,因为在迭代列表时更改列表会混淆 for 循环。 此外,如 razpeitia 所述,如果 item 是包含负整数的字符串,item.isdigit() 将不起作用。
【讨论】:
li = ['iterating + removing -> skipping', '4', '5', 'see?'](删除 4 将跳过 5,因此它保留在列表中)
您还可以使用 lambdas(显然还有递归)来实现(需要 Python 3):
isNumber = lambda s: False if ( not( s[0].isdigit() ) and s[0]!='+' and s[0]!='-' ) else isNumberBody( s[ 1:] )
isNumberBody = lambda s: True if len( s ) == 0 else ( False if ( not( s[0].isdigit() ) and s[0]!='.' ) else isNumberBody( s[ 1:] ) )
removeNumbers = lambda s: [] if len( s ) == 0 else ( ( [s[0]] + removeNumbers(s[1:]) ) if ( not( isInteger( s[0] ) ) ) else [] + removeNumbers( s[ 1:] ) )
l = removeNumbers(["hello", "-1", "2", "world", "+23.45"])
print( l )
结果(从 'l' 显示)将是:['hello', 'world']
【讨论】:
从列表中删除所有整数
ls = ['1','introduction','to','molecular','8','the','learning','module','5']
ls_alpha = [i for i in ls if not i.isdigit()]
print(ls_alpha)
【讨论】:
您可以使用内置的filter 来获取列表的过滤副本。
>>> the_list = ['1','introduction','to','molecular',-8,'the','learning','module',5L]
>>> the_list = filter(lambda s: not str(s).lstrip('-').isdigit(), the_list)
>>> the_list
['introduction', 'to', 'molecular', 'the', 'learning', 'module']
上面可以通过使用显式类型转换来处理各种对象。由于几乎每个 Python 对象都可以合法地转换为字符串,因此filter 为 the_list 的每个成员获取一个经过 str 转换的副本,并检查字符串(减去任何前导“-”字符)是否为数字。如果是,则从返回的副本中排除该成员。
The built-in functions are very useful. 它们每个都针对它们旨在处理的任务进行了高度优化,它们将使您免于重新发明解决方案。
【讨论】: