检查列表中的字符串,但带有通配符

时间:2021-10-22 20:06:09

I'm feeling RegEx is the way to go but I like the simplicity of my list so far and I'm not too in depth with RegEx just yet..

我觉得RegEx是要走的路,但到目前为止我喜欢我的列表的简单性,而且我还不太熟悉RegEx ...

I need to be able to cycle through this list:

我需要能够遍历此列表:

dat_list = ["Red_Ball","Yellow_Ball","Purple_Ball","Green_Ball"]

> "Red_Ball" in dat_list
    True

> "Purple_Turnip" in dat_list
    True

> "Beige_Sandwich" in dat_list
    False

I know I can also just check against the list but it won't check against it for wildcard strings like "Purple_Turnip"..

我知道我也可以检查列表,但它不会检查它是否像“Purple_Turnip”这样的通配符字符串。

1 个解决方案

#1


1  

Just checking for membership in a list (or set) is straightforward, but if you want to filter a list based on a pattern, you can't (trivially) gain the performance benefits of a hashtable lookup, so you might as well go back to list comprehensions.

只检查列表(或集合)中的成员资格很简单,但是如果要根据模式过滤列表,则不能(通常)获得散列表查找的性能优势,因此您可以返回列出理解。

[item for item in alist if re.match(expr, item)]

or

[item for item in alist if item.startswith(pat)]

or even

rx = re.compile(expr)
filter(rx.match, alist)

#1


1  

Just checking for membership in a list (or set) is straightforward, but if you want to filter a list based on a pattern, you can't (trivially) gain the performance benefits of a hashtable lookup, so you might as well go back to list comprehensions.

只检查列表(或集合)中的成员资格很简单,但是如果要根据模式过滤列表,则不能(通常)获得散列表查找的性能优势,因此您可以返回列出理解。

[item for item in alist if re.match(expr, item)]

or

[item for item in alist if item.startswith(pat)]

or even

rx = re.compile(expr)
filter(rx.match, alist)