合并两个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化的方式呢?

+2

有,但我不明白为什么你必须。 –

+4

两个'for循环'没有什么不对。你可以将它缩减为一行,但它不可读。 – MooingRawr

+0

'l = ['---完成时间----'如果h.complete和e.date

有没有把它写在一行

是一种方式。

或以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例子,它(而只剃毛一行离开原代码)在电报什么代码实际上做更好。