Pythonic结合两个FOR循环和IF语句的方法?

时间:2017-10-04 15:49:28

标签: python

我有这个循环:

for e in elements:
    for h in hs:
        if h.complete and e.date < h.date:
            print('----completed at time----',)

有没有办法用一行或以Pythonic的方式写它?

2 个答案:

答案 0 :(得分:2)

  

有没有办法把它写在一行

  

还是以Pythonic方式?

你目前拥有的是最恐怖的方式,这里不需要改变任何东西。

答案 1 :(得分:1)

有很多不同的方法可以将它缩小到更少的行 - 但是大多数方法的可读性会降低。例如:

  • not-really-list comprehension:[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示例,其中(虽然只从原始代码中删除一行)更能够直接显示代码实际执行的操作。