[英]Are there any shorter way for this way?
可以說我有變量a,b,c,d,e,f ..每次6個變量中的2個將隨機具有值= 0。 所以我的代碼是這樣的
if(a == 0 and b == 0):
run c,d,e,f
elif(a == 0 and c == 0):
run b,d,e,f
...
...
continue until end of all combination
所以編碼會很長,還有其他方法嗎?
您可以將所有數字放入列表中,然后將該列表的列表組合輸入到run
函數中-忽略為0的元素:
def run(p1,p2,p3,p4):
print(p1,p2,p3,p4)
# 3 test cases
for d in [ [ 1,2,0,3,4,0], [0,0,2,3,4,1], [4,3,0,2,1,0]]:
run(*[x for x in d if x]) # *[1,2,3] makes python provide the elements as params
輸出:
1 2 3 4
2 3 4 1
4 3 2 1
run( *[1,2,3])
與run(1,2,3)
相同 0
是Falsy-所以*[x for x in d if x]
對於d=[0,1,2,3,0]
僅使用d
中x
非偽值 : *[1,2,3]
run(*(x for x in d if x))
,則可以與生成器comp交換列表comp run(*[x for x in d if x])
中的run(*[x for x in d if x])
run(*(x for x in d if x))
以避免生成列表(不是這里重要;)) @Mehrdad Dowlatabadi提出了一個有趣的附帶問題-如果其他任何參數為0,則由於函數參數與列表推導中提供的參數之間不匹配而導致錯誤-您可以通過定義默認值來否定:
def run(p1=0, p2=0, p3=0, p4=0):
print(p1,p2,p3,p4)
因此,如果您將[0,1,2,0,0,0]
饋入它,它將仍然運行。
如果要使用未設置為0的變量運行函數,則可以首先列出不為0的元素
elements = [element for element in a, b, c, d, e if element !=0]
然后以元素列表作為參數調用該函數
run(*elements)
作為一個班輪:
run(*[element for element in a, b, c, d, e if element !=0])
生成運行清單:
def run(lst):
...
然后使用過濾器功能:
run(filter(None, [a, b, c, d, e, f]))
filter(None, lst)
刪除所有fals-y元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.