簡體   English   中英

是否有其他方法可以檢查python列表中特定索引的值是否為空

[英]Is there any alternative ways to check the value of particular index is empty or not in python list

def fn():
    return {'Name': 'John'}, False #, {'extra': 'welcome', 'to': 'dev@dsds.com'}

results, *returns = fn()

is_multiple = returns[0] if len(returns) > 0 else False
extra_params = returns[1] if len(returns) > 1 else None

print(is_multiple)
print(extra_params)

還有其他方法可以檢查extra_params是否為空嗎?

除了上述len解決方案之外,或者不使用try catch IndexError異常處理程序。

更好的解決方案是將函數返回的值定義為三個值元組,如果None值,則使用None或空dict ,例如:

def fn():
    return {'Name': 'John'}, False, None

results, is_multiple, extra_params = fn()

這要簡單得多,並且無需檢查長度。

例如,如果您正在編寫向后兼容的代碼,則可以選擇不對元組進行預先打包,例如:

def fn():
    return {'Name': 'John'}, False, # {}

response = fn()

# At least two items must be returned else length might not be valid.
if len(response) == 2:
    results, is_multiple = response
    extra_params = None
elif len(response) == 3:
    results, is_multiple, extra_params = response
else:
    raise ValueError("Unexpected response...")

盡管我建議第一種設計要簡單得多,但是有很多方法可以弄亂第二種設計並引起意外錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM