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
。什麼是優化解決方案?匹配這些字符串或列表的最佳方法是什麼?
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
。什麼是優化解決方案?匹配這些字符串或列表的最佳方法是什麼?
首先,您必須將輸入數字轉換爲字符串,因爲您對它們包含的數字感興趣,而不是實際值。您可以使用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)
+1 - 快速並且重點突出。 – 2010-12-11 17:48:39
也許使用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
+1我也喜歡。遵循正在發生的事情是很容易的。 – 2010-12-11 17:58:35
我已經在你的答案上發佈了一個細微的變化http://stackoverflow.com/questions/4418008/best-way-to-match-these-string-or-list/4418219#4418219 – jfs 2010-12-12 01:55:10
這裏有@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
+1:非常簡潔。 – unutbu 2010-12-12 12:13:25
*什麼是優化的解決方案* - 爲什麼優化?可讀性我假設(希望)? – 2010-12-11 17:38:00
你的意思是3個或更多數字匹配,2個或更少不匹配?它依賴於'len(str(match1))'嗎? – khachik 2010-12-11 17:39:03
main的值爲'123',因此如果任何字符串'3429523913'具有所有值1,2和3,則它匹配。這將檢查列表的所有元素並匹配元素中的數字。 – Tauquir 2010-12-11 17:42:43