How to generate permutations of a list without “reverse duplicates” in Python using generators

后端 未结 10 1159
情歌与酒
情歌与酒 2020-12-03 12:09

This is related to question How to generate all permutations of a list in Python

How to generate all permutations that match following criteria: if

10条回答
  •  盖世英雄少女心
    2020-12-03 12:41

    How about this:

    from itertools import permutations
    
    def rev_generator(plist):
        reversed_elements = set()
        for i in permutations(plist):
            if i not in reversed_elements:
                reversed_i = tuple(reversed(i))
                reversed_elements.add(reversed_i)
                yield i
    
    >>> list(rev_generator([1,2,3]))
    [(1, 2, 3), (1, 3, 2), (2, 1, 3)]
    

    Also, if the return value must be a list, you could just change the yield i to yield list(i), but for iteration purposes, the tuples will work just fine.

提交回复
热议问题