Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
删除Python列表中没有数字的单词的方法是什么?_Python_Regex - Fatal编程技术网

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

删除Python列表中没有数字的单词的方法是什么?,python,regex,Python,Regex,上面的列表中有历史之类的词,成员中没有数字,所以我想删除它们 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

上面的列表中有历史之类的词,成员中没有数字,所以我想删除它们

 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']

这里有一个较短的选择,使用
any()
string.digits

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']

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

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']

+1用于列表理解。@jon:你能简单地告诉我if-any(ch.isdigit())是如何工作的吗?尤其是“任何人”都会做什么。。Thanks@user1988876我们从列表中提取每个元素。然后从中提取每个字符,检查其中是否有数字-如果是,我们可以推断其为真,并将其添加到输出列表中。这意味着一旦找到数字,检查就会短路。(因此-对于第一个-我们只需要进入
1948
中的
1
就可以确定是否要包含它……)这里没有生成器。(而且,它也是一个没有正则表达式的单行程序。)修复。通过其他方法,它也是一个单行程序,这很好。从这些字符中的任何一个数字“到”都是这个字符串中的任何数字“可能在python中提供更好的性能”。
import re
[i for i in a if re.search('\d', i) is not None]