當你在一個 if 陳述句中有很多條件時,它通常被認為是寫得很糟糕的代碼嗎?我正在撰寫一些代碼內容(現在是 2020 年第 4 天),這似乎是解決我的問題的最簡單、最快的方法,但看起來有點奇怪。
def check_for_valid_passports(inp):
num_of_valid_passports = 0
for x in inp:
if "byr" in x and "iyr" in x and "eyr" in x and "hgt" in x and "hcl" in x and "ecl" in x and "pid" in x:
num_of_valid_passports = 1
return num_of_valid_passports
uj5u.com熱心網友回復:
我不會認為這是最好的答案(它也不是非常 Pythonic 抱歉),但我個人實作它的方式將如下所示。
def check_for_valid_passports(inp):
num_of_valid_passports = 0
for x in inp:
checks = ['bry', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'] # List of checks that need to pass
add = True # Default assumes all checks pass
for check in checks:
if check not in x:
add = False # If any of the checks fail then set a flag to false
if add:
num_of_valid_passports = 1
return num_of_valid_passports
我也沒有測驗這是否有效,因為我不知道輸入應該是什么樣子。
uj5u.com熱心網友回復:
您可以使用sum和all如下:
>>> def check_for_valid_passports(inp):
... return sum(all(s in i for s in (
... "byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"
... )) for i in inp)
...
>>> check_for_valid_passports(["byriyreyrhgthcleclpid", "foo", "pid", "byriyreyrhgthcleclpid"])
2
如果 的元素inp是集合(或者可以很容易地轉換為集合),您可以通過使用集合操作而不是all和來進一步簡化它in。
uj5u.com熱心網友回復:
您可以使用sumand重構它all:
def check_for_valid_passports(inp):
substrings = ("byr", "iyr", ..., "ecl", "pid")
return sum(1 for value in inp if all(substring in value for substring in substrings)))
對于每個單詞 W,生成器運算式將在每次 Wsubstrings中包含所有子字串時產生 1。然后您可以將所有這些 1 相加,回傳結果。
uj5u.com熱心網友回復:
我會認為這是糟糕的代碼。為什么?因為代碼質量關乎可讀性,關乎代碼是否易于理解和掌握,即使對于不是最初撰寫的人也是如此。
您可以使用 python 的內置功能撰寫更漂亮的代碼,類似于stackoverflow 中的這個答案:
def check_for_valid_passports(inp):
num_of_valid_passports = 0
for x in inp:
if all(foo in x for foo in ('byr', 'iyr', ...)):
num_of_valid_passports = 1
return num_of_valid_passports
然后你可以進一步改進它。你有一個只有一個簡單的 if 陳述句的 for 回圈,所以你可以考慮使用串列理解,如下所示:
def check_for_valid_passports(inp):
valid_items = ('byr', 'iyr', ...)
return len([inps for inps in inp if all([foo in inps for foo in valid_items])])
這實際上應該有效!對于這個,您可能會爭辯說,這不是可讀性的改進,所以是的……盡管對所做的事情有一個好的評論(和更好的變數名稱),這可能沒問題。
您應該真正考慮的一個重要方面是改進您的變數名稱!我想不出比這里的“foo”和“foobar”更好的了——為什么?因為您在原始代碼中使用了“inp”和“x”,而沒有給我機會去猜測那實際上是什么?;)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/365001.html
