简体   繁体   中英

How to sort itertools.product in Python?

This is Product from itertools:

product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy

But I wanna change to: --> Ax Bx Cx Dx Ay By Cy Dy How can I do that?

Change the order of arguments and reverse tuples product yields. It'll probably be more efficient than sorting, since it doesn't need to build intermediate list.

from itertools import product

def reorder_product(*a):
    for tup in product(*a[::-1]):
        yield tup[::-1]

Example:

print(*[''.join(t) for t in reorder_product('ABCD', 'xy')])
# Output:
#     Ax Bx Cx Dx Ay By Cy Dy

You'll probably be most efficient if you swap the order of the product and then simply reverse each of the yielded items:

def product_sorted_by_second(first, second):
    for item in itertools.product(second, first):
        yield item[::-1]

Of course, this is a horrible name for the function (since we aren't really sorting).

The advantage here is that you don't actually need to sort (which is an O(NlogN) processing step). So this ends up being an O(N) algorithm (where N is len(first) * len(second) )

not overly elegant but it works:

for p in product( 'xy', 'ABCD'):
    print(''.join(reversed(p)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM