2

我有一个清单:

mylist = ['summer_C','summer_C1','summer_P','summer_C123','summer_p32']

我想打印所有不以以下模式结尾的项目:

'_C' or '_C%' (int) 

所以它可能是'_C'或'_C1'或'_C2939'

我的尝试:

for item in mylist:
    if item[-2:] != '_C' or item[-x:] != '_C(INT)'
        print item

如您所见,它不是很动态,我该如何处理?

4

2 回答 2

2

您可以为此使用正则表达式:

import re

r = re.compile(r'_C\d+$')
mylist = ['summer_C','summer_C1','summer_P','summer_C123','summer_p32']
print [x for x in mylist if not r.search(x)]
#['summer_C', 'summer_P', 'summer_p32']

正则表达式解释:http ://regex101.com/r/wG3zZ2#python

于 2014-04-30T10:12:17.567 回答
0

您将使用正则表达式:

import re

numeric_tail = re.compile('_C\d*$')

for item in mylist:
    if not numeric_tail.search(item):
        print item

该模式匹配文字 text _C,后跟 0 个或多个数字,锚定在字符串的末尾 by $

演示:

>>> import re
>>> numeric_tail = re.compile('_C\d*$')
>>> mylist = ['summer_C','summer_C1','summer_P','summer_C123','summer_p32']
>>> for item in mylist:
...     if not numeric_tail.search(item):
...         print item
... 
summer_P
summer_p32
于 2014-04-30T10:12:07.797 回答