有沒有辦法優化這段代碼,讓它更短?
if user_input[0] == "f" or user_input[0:2] == "mu" or user_input[0:2] == "he" or user_input[-1] == "a":
我考慮過使用元組
inputcheck = ('f', 'mu', 'he', 'a')
但是在嘗試實際檢查不同的選項時會遇到問題
if user_input == inputcheck #This would of course not work
if user_input[0] == inputcheck #This may work, but 'a' needs to be checked at -1 index of string not at the start
uj5u.com熱心網友回復:
縮短它的一種方法是:
if user_input[0] == "f" or user_input[0:2] in ["mu", "he"] or user_input[-1] == "a":
允許in檢查串列值
uj5u.com熱心網友回復:
如果您不想使用正則運算式并且只想檢查前綴和后綴,則可以使用str.startswith和str.endswith,例如:
if user_input.startswith("mu")...
這樣,您不必將子字串范圍與前綴的長度相匹配。
測驗謂詞對于任何值串列是否為真的一種常用方法是使用 python 的內置any函式和生成器運算式:
if any(user_input.startswith(prefix) for prefix in ["f", "mu", "he"])...
如果您多次需要某些功能(正如您在評論中提到的那樣),您可以將其提取到一個函式中,例如:
PREFIXES = ("f", "mu", "he")
SUFFIXES = ("a",)
def check_user_input(user_input: str) -> bool:
return any(user_input.startswith(prefix) for prefix in PREFIXES) or any(
user_input.endswith(suffix) for suffix in SUFFIXES
)
uj5u.com熱心網友回復:
好吧,一個(骯臟的)解決方案可能是使用正則運算式,
import re
user_input = input()
if re.search(r"^f|^mu|^ha|a$",user_input):
print("works!!")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/517893.html
標籤:Python细绳优化元组
上一篇:如何使字串中的所有其他單詞都大寫
