main = ['123', '147', '159', '258', '369', '357', '456', '789']
match1 = 1开发者_Python百科374
match2 = 1892
here match1
has 1, 4 and 7 But main has '147' so it matches. match2
has 1,8,9,2 so it doesn't matches to main
. What is the optimize solution?
First you have to convert your inputs numbers to strings as you are interested in the digits they contain rather than actual values. You can use str
to do this.
To solve your actual problem you want to check if there is any string in main such that all the characters in that string are contained in the string match.
any(all(c in match for c in x) for x in main)
Here's a more complete test program:
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)
Output:
True False
If the one-liner is too much to absorb, you might want to split it up:
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)
Perhaps use sets
and check if one set is a subset of the other:
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
Here's variation on @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
Where map = itertools.imap
精彩评论