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

后端 未结 5 1811
心在旅途
心在旅途 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:00

    This is an approach based on the observation that it is easier to generate the negatives of the indices in the (reverse of) the desired order It is similar to the approach of @Divakar and like that has the drawback of requiring the list to be created in memory:

    def decreasingTuples(N,k):
        for t in reversed(list(itertools.combinations(range(1-N,1),k))):
            yield tuple(-i for i in t)
    
    >>> for t in decreasingTuples(4,2): print(t)
    
    (1, 0)
    (2, 0)
    (2, 1)
    (3, 0)
    (3, 1)
    (3, 2)
    >>> for t in decreasingTuples(4,3): print(t)
    
    (2, 1, 0)
    (3, 1, 0)
    (3, 2, 0)
    (3, 2, 1)
    

提交回复
热议问题