[英]Pythonic way to combine two FOR loops and an IF statement?
我有這個循環:
for e in elements:
for h in hs:
if h.complete and e.date < h.date:
print('----completed at time----',)
有沒有一種方法可以單行或以Python方式編寫它?
有沒有辦法一行寫
是。
還是以Python的方式?
您目前擁有的是最Python化的方式,無需在此處進行任何更改。
有很多不同的方法可以將其縮小為更少的行-但其中大多數將不太可讀。 例如:
並非真正的列表理解: [print('whatever') for e in elements for h in hs if e.date < h.date]
列表for p in [sth(e, h) for e in elements for h in hs if e.date < h.date]: print(p)
: for p in [sth(e, h) for e in elements for h in hs if e.date < h.date]: print(p)
使用itertools.product
:
for e, h in product(elements, hs): if h.complete and e.date < h.date: print('whatever')
與上述相同,但帶有filter
:
for e, h in filter(lambda e, h: h.complete and e.date < h.date, product(elements, hs)): print('whatever')
編輯 :我個人的偏愛在於第一個product
示例,該示例(雖然只將原始代碼削了一行)更適合於說明代碼的實際作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.