[英]python multiple assignment readability
一個簡單的問題-但我似乎無法通過Google找到任何東西...
可以說我有兩個獨立設置的變量。 它們應該具有相同的值。 現在,這兩個變量將在一個新函數中找到並准備好組合。
首先,我要確保它們相同。 然后,我想將第三個變量(id)設置為兩個變量(id_1,id_2)的值,以使代碼更清晰。
id_1=5
id_2=5
# ensure id_1==id_2
assert id_1 == id_2
id=id_1 # option 1
id=id_2 # option 2
id=id_1=id_2 # option 3
什么是正確的“ pythonic”方法? 最易讀的是什么? 還是有更好的方法來做到這一點(並擴展到> 2個初始變量)? 以前我曾經使用過(選項1)。
def f(*args):
if args[1:] == args[:-1]: #test all args passed are equal
id = args[0] #set your 'id' to the first value
else:
return None # just as an example
# do things ...
return id
>>> f(1,2,3,4)
None
>>> f(1,1,1,1)
1
我會做:
try:
id = id1 if id1==id2 else int('')
except ValueError as e:
#fix it or
raise ValueError('id1 and id2 are different.') from e
對於多個值:
try:
id = args[0] if len(set(args))==1 else int('')
except ValueError as e:
#fix it or
raise ValueError('id1 and id2 are different.') from e
我通常保持斷言用於調試目的,因此使用try語句。
我將其他函數定義為列表,而不是一堆您不需要的變量,然后使用any
來檢查它們是否匹配。 您不需要將每個值都與其他值進行比較,只需將第一個值與所有其他值進行比較:
id, *rest = list_of_values # this is Python 3 syntax, on earlier versions use something
# like `id, rest = list_of_values[0], list_of_values[1:]`
assert(all(id == other_id for other_id in rest))
# do stuff here with `id`
請注意, id
實際上並不是變量的好名字,因為它也是內置函數的名稱(您的代碼將被遮蓋,因此您的代碼將無法使用)。 如果您的id
代表某種特定類型的對象,則可以使用foo_id
類的名稱來更明確地說明其用途。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.