合并两个FOR循环和一个IF语句的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