-2

all

a = ['T01--X','T02--X','T03--X','T04--XX','T01--X','T01--Y','T05--X','T02-YY','T01-T02','T02-T03']

how to match str including T01 or T02 or T03 in this list?

thanks in advance

Robbie
  • 53
  • 1
  • 8

3 Answers3

1
a = ['T01--X','T02--X','T03--X','T04--XX','T01--X','T01--Y','T05--X','T02-YY','T01-T02','T02-T03']

for i in a:
    if 'T01' in i or 'T02' in i or 'T03' in i :
        print(i)

out:

T01--X
T02--X
T03--X
T01--X
T01--Y
T02-YY
T01-T02
T02-T03
宏杰李
  • 11,820
  • 2
  • 28
  • 35
1

Method 1

Using simple for and if loop.

a = ['T01--X','T02--X','T03--X','T04--XX','T01--X','T01--Y','T05--X','T02-YY','T01-T02','T02-T03']

result = []
for element in a:
     if 'T01' in element or 'T02' in element or 'T03' in element :
             result.append(element)
print result

Method 2

Using list comprehension. A more pythonic way!

a = ['T01--X','T02--X','T03--X','T04--XX','T01--X','T01--Y','T05--X','T02-YY','T01-T02','T02-T03']
print [elt for elt in a if 'T01' in elt or 'T02' in elt or 'T03' in elt]

Hope this helps!

bharadhwaj
  • 2,059
  • 22
  • 35
  • `if 'T01' in element or 'T02' in element or 'T03' in element` could be reduced to `if element in ('T01', 'T02', 'T03')`. – Christian Dean Dec 13 '16 at 07:18
  • @leaf Are you sure? The logic seems reversed for me! Your code will search for element which is same as 'T01' or 'T02' or 'T03'. But it doesn't look like, it will find sub string. Please correct me if I am wrong. – bharadhwaj Dec 13 '16 at 08:09
  • Actual, your right. My example above will not work. I forgot to cut the first three characters from `element`. **This will work however**: `if element[0:3] in ('T01', 'T02', 'T03')`. For more info behind this see [How do I test one variable against multiple values?](http://stackoverflow.com/questions/15112125/how-do-i-test-one-variable-against-multiple-values). – Christian Dean Dec 13 '16 at 08:13
  • Yeah! Your method works great when checking **equality**, I suppose! Still for checking sub string, I prefer basic ```if``` statement with many ```or``` and/or ```and```. I would also prefer using ```any``` method, as MSeifert used here! Anyway thanks @leaf, I learned a new way on checking equality. – bharadhwaj Dec 13 '16 at 08:21
  • Python & function-ish: `result = [i for i in a if any(map(lambda x: x in i, ['T01', 'T02', 'T03']))]` |OR| `result = list(filter(lambda i: any([x in i for x in ('T01', 'T02', 'T03',)]), a))` – Lopofsky Feb 06 '22 at 12:44
0

You mean something like a conditional list comprehension?

In that case you could use:

>>> [item for item in a if any(substr in item for substr in ['T01', 'T02', 'T03'])]
['T01--X', 'T02--X', 'T03--X', 'T01--X', 'T01--Y', 'T02-YY', 'T01-T02', 'T02-T03']
MSeifert
  • 145,886
  • 38
  • 333
  • 352