删除Python列表中没有数字的单词的方法是什么?

2024-10-03 19:31:59 发布

您现在位置:Python中文网/ 问答频道 /正文

 a = ['in 1978 by', 'History', 'members', 'albums', 'June 4th, 1979', 'October 7,1986): "The Lounge', 'In 1984 the', 'early 1990s; prominent']

上面的列表有一些单词,比如历史,成员中没有数字,所以我想删除它们

 # output would be
 a = ['in 1978 by', 'June 4th, 1979', 'October 7, 1986', 'In 1984 the', 'early 1990s; prominent']

Tags: thein列表by单词historymembersalbums
3条回答

使用正则表达式和列表理解,这是一行:

import re
[i for i in a if re.search('\d', i) is not None]

保留你想要的:

a = ['in 1978 by', 'History', 'members', 'albums', 'June 4th, 1979', 'October 7,1986): "The Lounge', 'In 1984 the', 'early 1990s; prominent']

new = [el for el in a if any(ch.isdigit() for ch in el)]
# ['in 1978 by', 'June 4th, 1979', 'October 7,1986): "The Lounge', 'In 1984 the', 'early 1990s; prominent']

下面是一个较短的替代方法,使用any()string.digits

from string import digits

a = ['in 1978 by', 'History', 'members', 'albums', 'June 4th, 1979', 
     'October 7,1986): "The Lounge', 'In 1984 the', 'early 1990s; prominent']

[x for x in a if any(y in x for y in digits)]

=> ['in 1978 by', 'June 4th, 1979', 'October 7,1986): "The Lounge',
    'In 1984 the', 'early 1990s; prominent']

相关问题 更多 >