2010-12-11 37 views
2
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。什么是优化解决方案?匹配这些字符串或列表的最佳方法是什么?

+4

*什么是优化的解决方案* - 为什么优化?可读性我假设(希望)? – 2010-12-11 17:38:00

+0

你的意思是3个或更多数字匹配,2个或更少不匹配?它依赖于'len(str(match1))'吗? – khachik 2010-12-11 17:39:03

+0

main的值为'123',因此如果任何字符串'3429523913'具有所有值1,2和3,则它匹配。这将检查列表的所有元素并匹配元素中的数字。 – Tauquir 2010-12-11 17:42:43

回答

4

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

解决您最实际的问题要检查是否有任何主这样所有在字符串中的字符都包含在字符串匹配

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 

如果一个班轮过多吸收,你可能要拆呢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) 
+0

+1 - 快速并且重点突出。 – 2010-12-11 17:48:39

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 
+0

+1我也喜欢。遵循正在发生的事情是很容易的。 – 2010-12-11 17:58:35

+0

我已经在你的答案上发布了一个细微的变化http://stackoverflow.com/questions/4418008/best-way-to-match-these-string-or-list/4418219#4418219 – jfs 2010-12-12 01:55:10

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

+0

+1:非常简洁。 – unutbu 2010-12-12 12:13:25

相关问题