匹配字符串末尾的模式?

时间:2021-07-26 21:43:33

Imagine I have the following strings:

想象一下,我有以下字符串:

['a','b','c_L1', 'c_L2', 'c_L3', 'd', 'e', 'e_L1', 'e_L2']

Where the "c" string has important sub-categories (L1, L2, L3). These indicate special data for our purposes that have been generated in a program based a pre-designated string "L". In other words, I know that the special entries should have the form:

其中“c”字符串具有重要的子类别(L1,L2,L3)。这些表示用于我们目的的特殊数据,这些数据是在基于预先指定的字符串“L”的程序中生成的。换句话说,我知道特殊条目应该具有以下形式:

name_Lnumber

Knowing that I'm looking for this pattern, and that I am using "L" or more specifically "_L" as my designation of these objects, how could I return a list of entries that meet this condition? In this case:

知道我正在寻找这种模式,并且我使用“L”或更具体的“_L”作为我对这些对象的指定,我怎么能返回满足这个条件的条目列表?在这种情况下:

['c', 'e']

2 个解决方案

#1


4  

Use a simple filter:

使用简单的过滤器:

>>> l = ['a','b','c_L1', 'c_L2', 'c_L3', 'd', 'e', 'e_L1', 'e_L2']

>>> filter(lambda x: "_L" in x, l)
['c_L1', 'c_L2', 'c_L3', 'e_L1', 'e_L2']

Alternatively, use a list comprehension

或者,使用列表理解

>>> [s for s in l if "_L" in s]
['c_L1', 'c_L2', 'c_L3', 'e_L1', 'e_L2']

Since you need the prefix only, you can just split it:

由于您只需要前缀,您可以将其拆分:

>>> set(s.split("_")[0] for s in l if "_L" in s)
set(['c', 'e'])

#2


3  

you can use the following list comprehension :

你可以使用以下列表理解:

>>> set(i.split('_')[0] for i in l if '_L' in i)
set(['c', 'e'])

Or if you want to match the elements that ends with _L(digit) and not something like _Lm you can use regex :

或者,如果要匹配以_L(数字)结尾的元素而不是像_Lm那样的元素,则可以使用正则表达式:

>>> import re
>>> set(i.split('_')[0] for i in l if re.match(r'.*?_L\d$',i))
set(['c', 'e'])

#1


4  

Use a simple filter:

使用简单的过滤器:

>>> l = ['a','b','c_L1', 'c_L2', 'c_L3', 'd', 'e', 'e_L1', 'e_L2']

>>> filter(lambda x: "_L" in x, l)
['c_L1', 'c_L2', 'c_L3', 'e_L1', 'e_L2']

Alternatively, use a list comprehension

或者,使用列表理解

>>> [s for s in l if "_L" in s]
['c_L1', 'c_L2', 'c_L3', 'e_L1', 'e_L2']

Since you need the prefix only, you can just split it:

由于您只需要前缀,您可以将其拆分:

>>> set(s.split("_")[0] for s in l if "_L" in s)
set(['c', 'e'])

#2


3  

you can use the following list comprehension :

你可以使用以下列表理解:

>>> set(i.split('_')[0] for i in l if '_L' in i)
set(['c', 'e'])

Or if you want to match the elements that ends with _L(digit) and not something like _Lm you can use regex :

或者,如果要匹配以_L(数字)结尾的元素而不是像_Lm那样的元素,则可以使用正则表达式:

>>> import re
>>> set(i.split('_')[0] for i in l if re.match(r'.*?_L\d$',i))
set(['c', 'e'])