對於不好的標題表示歉意。我不確定如何說出我的問題。 我有下面的代碼使用稱爲propadd
的元組列表。 if statement
測試元組的匹配條件。如果匹配只匹配元組列表中的1個元組,它將執行與if語句中相同的代碼,以便將此匹配元組分配給變量v,以便用來自此匹配元組的值更新遊標行。我想知道是否有辦法擺脫if語句後與v完全相同的代碼的賦值。在檢查匹配的長度時,是否可以在if語句中將列表分配給v?這是遵循這種方法的大量代碼的一部分。我相信這樣做會使我的代碼更快。分配變量名稱以列出if語句python
if len([item for item in propadd if item[0]==row1[8] and harversine(custx,custy,item[2],item[3])<1500]) == 1:
v=[item for item in propadd if item[0]==row1[8] and harversine(custx,custy,item[2],item[3])<1500]
row1[1]=v[0][1]
row1[2]=v[0][2]
elif len([item for item in custadd if item[0]==row1[4]]) == 1:
k=[item for item in custadd if item[0]==row1[4]]
row1[1]=k[0][1]
row1[2]=k[0][2]
elif len([item for item in numlist if re.search(r"^[0-9]+(?=\s)",row1[0]) is not None and item[0]==re.search(r"^[0-9]+(?=\s)",row1[0]).group()]) == 1
m=[item for item in numlist if re.search(r"^[0-9]+(?=\s)",row1[0]) is not None and item[0]==re.search(r"^[0-9]+(?=\s)",row1[0]).group()]
row1[1]=m[0][1]
row1[2]=m[0][2]
如果你想讓你的代碼更快,我相信使用'filter'函數比列表comp更快。當我打字的時候,@MadPhysicist發佈了我要說的話:你可以分配'v'然後檢查'len(v)',這樣list comp只運行一次 –
我會研究'filter'函數。謝謝。 – ketar