简体   繁体   中英

pattern match list a with list b

I am fairly new to Python.

I have two lists

List A [a, b, c]
List B [c,d,e,f,g,h]

I would like to re.match (or re.search) list A variables in list B. If any variable from list A not present in List B, it should return false.

In above lists, it should return false.

Can I try for loop as below ?

for x in listA:
if re.match(listB, x)
return false

You can use all :

>>> lis1 =  ['a', 'b', 'c'] 
>>> lis2 =  ['c','d','e','f','g','h']
>>> all(x in lis2 for x in lis1)
False

If lis2 is huge convert it to a set first, as sets provide O(1) lookup:

>>> se = set(lis2)
>>> all(x in se for x in lis1)
False

Regular expressions don't work on lists.

This sounds like a job for sets, not regular expressions:

 set(listA) & set(listB) == set(listA)

The above is stating: if the intersection of the two sets has the same elements than the first set, then all of the first set's elements are also present in the second set. Or, as Jon points out, a solution based in set difference is also possible:

 not set(listA) - set(listB)

The above states: If there are no elements that are in the first set that are not present in the second set, then the condition holds (sorry about the double negation!)

Just iterate over the lists, and use all .

>>> llist = "a b c".split()
>>> rlist = "c d e".split()
>>> all(re.match(left, right) for left in llist for right in rlist)
False

This only becomes interessant if llist contains "true" regexps:

>>> llist = [r"^.+foo$", r"^bar.*$"]
>>> rlist = ["foozzz", "foobar"]
>>> all(re.match(left, right) for left in llist for right in rlist)
False

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