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

时间:2010-12-11 17:36:15

标签: python

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

match1 = 1374
match2 = 1892

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

3 个答案:

答案 0 :(得分:4)

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

要解决您的实际问题,您需要检查main中是否有任何字符串,以便所有该字符串中的字符 >字符串匹配。

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

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

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

match1 = str(1374)
match2 = str(1892)

def has_any_match(main, match):
    return any(all(c in match for c in x) for x in main)

print has_any_match(main, match1)
print has_any_match(main, match2)

输出:

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)

答案 1 :(得分:4)

也许使用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

答案 2 :(得分:1)

以下是@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