Вопрос

I have a list:

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

I want to print all items which do not end with the following pattern:

'_C' or '_C%' (int) 

so it could be something like '_C' or '_C1' or '_C2939'

My attempt:

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

As you can see its not very dynamic, how can I approach this?

Это было полезно?

Решение 2

You'd use a regular expression:

import re

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

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

The pattern matches the literal text _C, followed by 0 or more digits, anchored at the end of the string by $.

Demo:

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

Другие советы

You can use regex for this:

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

Regex explanation: http://regex101.com/r/wG3zZ2#python

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top