我有這樣的循環:合併兩個FOR循環和一個IF語句的Python方法?
for e in elements:
for h in hs:
if h.complete and e.date < h.date:
print('----completed at time----',)
有沒有把它寫在一個行或Python化的方式呢?
我有這樣的循環:合併兩個FOR循環和一個IF語句的Python方法?
for e in elements:
for h in hs:
if h.complete and e.date < h.date:
print('----completed at time----',)
有沒有把它寫在一個行或Python化的方式呢?
有沒有把它寫在一行
是一種方式。
或以Pythonic的方式嗎?
你目前已經是最Pythonic的方式,不需要在這裏改變任何東西。
有很多不同的方法可以將這個縮小到更少的行 - 但其中大多數會減少可讀性。例如:
未真正列表理解:[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)
使用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
例子,它(而只剃毛一行離開原代碼)在電報什麼代碼實際上做更好。
有,但我不明白爲什麼你必須。 –
兩個'for循環'沒有什麼不對。你可以將它縮減爲一行,但它不可讀。 – MooingRawr
'l = ['---完成時間----'如果h.complete和e.date