简体   繁体   中英

Compare two lists of different strings

I would like to compare two lists of strings, but the items in the first one will be part of the items of the second one. I give you an example:

list01 = ['test_item01','test_item02','truc_item03']
list02 = ['_item01','truc']

I would like to have something like

if list02 not in list01:
    #do that

What I really want it's that 'test_item01' and '_item01' are interpreted as the same like they have a part in common.

I tried different things but nothing works.

if not all(any(x in y for y in list01) for x in list02):
    print 'do that'

note that the functionality of all/any here guarantees good performance. Once a single superstring is found for an element of list02 , the inner loop represented by any stops, and once an element of list02 is found that has no superstring, we stop checking the rest of list02

This can be done also using sets intersection:

def intersect(a, b):
    return list(set(a) & set(b))

iSec = intersect(list01, list02)
if len(iSec) == len(list02):
    print 'contains'
else:
    print 'not contains'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM