匹配这些字符串或列表的最佳方法是什么?

2024-06-16 10:49:04 发布

您现在位置:Python中文网/ 问答频道 /正文

main = ['123', '147', '159', '258', '369', '357', '456', '789']

match1 = 1374
match2 = 1892

这里match1有1、4和7,但main有“147”,所以它匹配。match2有1,8,9,2,因此它与main不匹配。什么是优化解决方案?


Tags: main解决方案match1match2
3条回答

首先,您必须将输入的数字转换成字符串,因为您对它们包含的数字感兴趣,而不是实际值。您可以使用str来执行此操作。在

为了解决实际问题,您需要检查main中是否存在任何字符串,以便该字符串中的所有字符都包含在字符串匹配中。在

any(all(c in match for c in x) for x in main)

下面是一个更完整的测试程序:

^{pr2}$

输出:

True
False

如果一行代码太多而无法吸收,您可能需要将其拆分:

def is_match(word, match):
    # Test if all the characters in word are also in match.
    return all(c in match for c in word)

def has_any_match(main, match):
    # Test if there is any word in main that matches.
    return any(is_match(word, match) for word in main)

以下是@unutbu's answer的变体:

>>> main = ['123', '147', '159', '258', '369', '357', '456', '789']
>>> match1 = '1374'
>>> match2 = '1892'
>>> any(map(set(match1).issuperset, main))
True
>>> any(map(set(match2).issuperset, main))
False

其中map = itertools.imap

也许使用sets检查一个集合是否是另一个集合的子集:

main = ['123', '147', '159', '258', '369', '357', '456', '789']
main = map(set,main)
match1 = set('1374')
match2 = set('1892')
print(any(elt.issubset(match1) for elt in main))
# True

print(any(elt.issubset(match2) for elt in main))
# False

相关问题 更多 >