简体   繁体   English

模式匹配列表a与列表b

[英]pattern match list a with list b

I am fairly new to Python. 我对Python相当陌生。

I have two lists 我有两个清单

List A [a, b, c] 清单A [a,b,c]
List B [c,d,e,f,g,h] 清单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. 我想重新匹配(或重新搜索)列表B中的列表A变量。如果列表B中不存在列表A中的任何变量,则应返回false。

In above lists, it should return false. 在上面的列表中,它应该返回false。

Can I try for loop as below ? 我可以尝试以下循环吗?

for x in listA: 对于listA中的x:
if re.match(listB, x) 如果re.match(listB,x)
return false 返回假

You can use all : 您可以使用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: 如果lis2很大,则首先将其转换为set ,因为集合提供了O(1)查找:

>>> 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: 或者,正如乔恩(Jon)所指出的,基于集合差异的解决方案也是可行的:

 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 . 只需遍历列表,然后使用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包含“ true”正则表达式,这只会引起问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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