我認爲將5個參數放在列表中會更方便。然後,該功能可適用於任何尺寸的手。你想匹配的牌可以進入一個名單,matching_cards
,這也將適用於任何規模。
Python的換別的語法將很好地工作這種類型的應用:如果你正在尋找確切的字符串匹配
def matching(hand, matching_cards):
for card in matching_cards:
if card not in hand:
print("Nothing found!") # Every card needs to be in the hand
break
else: # Every card was found in hand, break never executed
print("Match detected!")
,此功能會工作。但是,如果您想匹配手中的部分字符串(例如,您正在使用諸如"Two"
之類的短字匹配"Two of Spades"
和"Two of Hearts"
之類的卡),則該功能更爲先進。我看到兩種方法可以解決這個問題:
def matching(hand, matching_phrases):
for phrase in matching_phrases:
for card in hand:
if phrase in card: # Phrase must be in string of at least one card
break # Once phrase is found in one string, break
else: # Otherwise, phrase was never found in any of the cards. No match
print("Nothing found!")
break
else: # Every phrase was found in hand, break never executed
print("Match detected!")
或者使用更類似於@ndpu的樣式。對於matching_phrases
中的每個phrase
,該函數檢查card
的any
是否包含phrase
。對於要執行的if
聲明,all
phrase
必須位於其中一張卡片中。
def matching(hand, matching_phrases):
if all(any(phrase in card for card in hand) for phrase in matching_phrases):
print("Match detected!")
else:
print("Nothing found!")
感謝您的回覆,也會考慮這個選項,這似乎是一個可能的選擇。 – Russman