Iterating over multiple indices with i > j ( > k) in a pythonic way

后端 未结 5 1770
心在旅途
心在旅途 2021-01-04 03:21

i need to iterate over a tuple of indices. all indices must be in the range [0, N) with the condition i > j. The toy example I present here deal

5条回答
  •  囚心锁ツ
    2021-01-04 04:13

    You can use product from itertools if you don't mind the inefficiency of throwing out most of the generated tuples. (The inefficiency gets worse as the repeat parameter increases.)

    >>> from itertools import product
    >>> for p in ((i,j) for (i,j) in product(range(5), repeat=2) if i > j):
    ...   print p
    ...
    (1, 0)
    (2, 0)
    (2, 1)
    (3, 0)
    (3, 1)
    (3, 2)
    (4, 0)
    (4, 1)
    (4, 2)
    (4, 3)
    >>> for p in ((i,j,k) for (i,j,k) in product(range(5), repeat=3) if i > j > k):
    ...   print p
    ...
    (2, 1, 0)
    (3, 1, 0)
    (3, 2, 0)
    (3, 2, 1)
    (4, 1, 0)
    (4, 2, 0)
    (4, 2, 1)
    (4, 3, 0)
    (4, 3, 1)
    (4, 3, 2)
    

    Update: Instead of tuple unpacking, using indexing for the filter. This allows the code to be written a little more compactly. Only my_filter needs to be changed for tuples of varying sizes.

    from itertools import product, ifilter
    def my_filter(p):
        return p[0] > p[1] > p[2]
    
    for p in ifilter(my_filter, product(...)):
        print p
    

提交回复
热议问题