[英]What is the way to delete words in Python list which does not have numbers?
a = ['in 1978 by', 'History', 'members', 'albums', 'June 4th, 1979', 'October 7,1986): "The Lounge', 'In 1984 the', 'early 1990s; prominent']
the above list have words like history, members which do not have numbers in them, so i want to delete them 上面的列表有像历史,成员没有数字的单词,所以我想删除它们
# output would be
a = ['in 1978 by', 'June 4th, 1979', 'October 7, 1986', 'In 1984 the', 'early 1990s; prominent']
Keep the ones you want: 保留你想要的:
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']
Here's a shorter alternative, using any()
and string.digits
: 这是一个较短的替代方案,使用
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']
Using a regular expression and a list comprehension, this is a one-liner: 使用正则表达式和列表理解,这是一个单行:
import re
[i for i in a if re.search('\d', i) is not None]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.