我正在尝试验证列表中的每个字符串在另一个列表中是否至少存在一次。我经常遇到的问题是字符串永远不会完全匹配,所以我需要某种形式的regex/globbing。你知道吗
must_have_list = ['APPLE SSD', 'APPLE HDD']
example_device_list = [u'APPLE SSD SM128E', u'APPLE HDD HTS541010A9E662']
example_device_list2 = [u'APPLE SSD SD0128F', u'APPLE HDD ST3000DM001']
如果给定的设备列表至少包含来自must_have_list
的每个设备字符串中的一个,则返回True
。如果给定的设备列表只包含must_have_list
中的一个(或没有)项,则返回False
[u'APPLE SSD SM128E', u'APPLE HDD HTS541010A9E662']
True
找到每个
[u'APPLE HDD HTS541010A9E662', u'APPLE HDD HTS541010A9E662']
False
仅找到2xAPPLE HDD
,未列出APPLE SSD
[u'APPLE HDD HTS541010A9E662', u'APPLE HDD HTS541010A9E662', u'APPLE SSD SM128E']
True
每个都找到一个,即使有多个APPLE HDD
[u'APPLE SSD SM128E']
False
仅列出APPLE SSD
,未列出APPLE HDD
如何使用regex验证一个列表中的每个项目是否存在于另一个列表中?你知道吗
不使用
regex
。这是一种使用str.startswith()
解决问题的方法:输出:
您可以使用
all
和any
来测试您的条件:印刷品:
可与列表理解一起使用,以生成符合条件的列表:
在这种情况下不需要regex,但是如果测试每个字符串都需要regex,则可以使用
re.search
而不是in
。你知道吗例如,假设您想知道被测试的子字符串是独立的,而不是另一个单词的一部分,比如
SSDHYBRID
:如您的示例所示,如果要测试的模式始终是字符串的初始部分,则比较简单:
如果它可以是一个内部字符串,那么就必须使用
must_have in example
而不是startswith,这增加了算法的复杂性。你知道吗额外的优化将是删除一个示例设备,发现它没有测试其他必备品。你知道吗
最后,您可以将整个过程翻过来,遍历每个示例设备上的示例列表,删除一个musthave作为本示例的前缀,直到没有musthave为止。根据必有列表和示例列表的大小,将必有列表复制到新的dict(或集合中的集合)以缩短搜索时间是有意义的。你知道吗
相关问题 更多 >
编程相关推荐