我從來沒有找到一種簡潔方法做的事情是將字符串與多個集合進行比較,或者可以使用一個長的字符串來提供一些有意義的輸出。這是我目前的代碼:Python簡潔性:將字符串與具有返回值的多個集合進行比較
def input():
text = input("Choose a number: ").lower()
if "1" in text or "one" in text: return 1
elif "2" in text or "two" in text: return 2
... and so on...
elif "9" in text or "nine" in text: return 9
else: return 0
我的目標是讓它更簡潔一點,考慮它現在有多醜。
此外,在問題標籤的一點點:這是更快地做到這一點,或:
if any(x in text for x in (["1", "one"])): return 1
哪一個被認爲是更主流?
對不起;我的Python確實是入門級的。
---編輯---
道歉的混亂;我其實是一些更普遍意義,比如這個:
def input():
text = input("Give an input: ").lower()
if any(x in text for x in (["eggplant", "emoji", "purple"])): return 1
elif any(x in text for x in (["tomato", "red", "tomatina"])): return 2
... and so on...
elif any(x in text for x in (["lettuce", "green", "avatar"])): return 9
else: return 0
也許是正則表達式? 此外,輸入可能只是一個數字或一個數字(不是「短語」)?你能做出這些假設嗎? – Aviad
對不起,這不是我原來的代碼;我只是用一種表達我的意思的格式。輸入將是一個字符串。我對我缺乏Python專業知識表示歉意,但我真的不知道如何使用正則表達式;你能給我一個小例子嗎? – XymphosCraK