Python 正则表达式:在列表中搜索

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3640359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:02:47  来源:igfitidea点击:

Regular Expressions: Search in list

pythonregex

提问by leoluk

I want to filter strings in a list based on a regular expression.

我想根据正则表达式过滤列表中的字符串。

Is there something better than [x for x in list if r.match(x)]?

有比 更好的[x for x in list if r.match(x)]吗?

采纳答案by sepp2k

You can create an iteratorin Python 3.x or a listin Python 2.x by using:

您可以使用以下命令在 Python 3.x 中创建迭代器或在 Python 2.x 中创建列表

filter(r.match, list)

To convert the Python 3.x iteratorto a list, simply cast it; list(filter(..)).

要将 Python 3.x迭代器转换为列表,只需将其强制转换即可;list(filter(..)).

回答by Mercury

Full Example (Python 3):
For Python 2.x look into Note below

完整示例(Python 3):
对于 Python 2.x,请查看下面的注释

import re

mylist = ["dog", "cat", "wildcat", "thundercat", "cow", "hooo"]
r = re.compile(".*cat")
newlist = list(filter(r.match, mylist)) # Read Note
print(newlist)

Prints:

印刷:

['cat', 'wildcat', 'thundercat']


Note:

笔记:

For Python 2.x users, filterreturns a list already. In Python 3.x filterwas changed to return an iterator so it has to be converted to list(in order to see it printed out nicely).

对于 Python 2.x 用户,filter已经返回一个列表。在Python 3.x 中filter已更改为返回迭代器,因此必须将其转换为list(以便看到它很好地打印出来)。

Python 3 code example
Python 2.x code example

Python 3 代码示例
Python 2.x 代码示例