如何删除列表中的数字并保持元素的重置? Python

How to remove numbers in a list and keep reset of the elements? Python

mylist = ['85639-Joe','653896-Alan','8871203-Zoe','5512-Bob','81021-Jonathan']

上面是列表,我想删除列表中的数字并保留名称。 我尝试了下面的编码,但没有用。

[s for s in mylist if s.isalpha()]

预期的输出是:

['-Joe','-Alan','-Zoe','-Bob','-Jonathan']

在此先感谢您的帮助。

我们可以使用正则表达式来删除数字,如

import re

[re.sub('\d', '', s) for s in mylist]

给予

['-Joe', '-Alan', '-Zoe', '-Bob', '-Jonathan']

您可以为此使用正则表达式

import re

mylist = ['85639-Joe','653896-Alan','8871203-Zoe','5512-Bob','81021-Jonathan']

print([re.sub(r'\b\d+\b', '', word) for word in mylist])

输出:

['-Joe', '-Alan', '-Zoe', '-Bob', '-Jonathan']

这是不使用正则表达式的另一种方法:

[''.join(y for y in x if not y.isdigit()) for x in mylist]

结果:

['-Joe', '-Alan', '-Zoe', '-Bob', '-Jonathan']

如果您为可选的 chars 参数传递一串数字,内置的 lstrip function 可以执行此操作。

无论您决定采用哪种技术,请考虑制作一个辅助函数来完成这项工作。您代码的未来维护者会感谢您。

mylist = ['85639-Joe','653896-Alan','8871203-Zoe','5512-Bob','81021-Jonathan']
mylist.append('29-Biff42Henderson') # corner case

def strip_numeric_prefix(s: str):
    return s.lstrip('0123456789')

result = [strip_numeric_prefix(s) for s in mylist]
print(result)
#output
['-Joe', '-Alan', '-Zoe', '-Bob', '-Jonathan', '-Biff42Henderson']
mylist = ['85639-Joe','653896-Alan','8871203-Zoe','5512-Bob','81021-Jonathan']

temp = ['-'+e.split('-')[1] for e in mylist]

结果 ['-Joe', '-Alan', '-Zoe', '-Bob', '-Jonathan']