Home  >  Article  >  Backend Development  >  How to efficiently scramble the tuples generated by itertools.combinations()?

How to efficiently scramble the tuples generated by itertools.combinations()?

PHPz
PHPzforward
2024-02-22 12:43:11648browse

如何有效地打乱 itertools.combinations() 生成的元组?

Question content

I am using itertools.combinations() to generate a list of two-item tuples based on a list of non-repeating elements. Then I shuffle the resulting list. However, the contents of the tuple itself are organized chronologically. For example, run the following code:

import random
import itertools
items = ["a","b","c","d","e"]
item_combos = list(itertools.combinations(items, 2))
random.shuffle(item_combos)
print(item_combos)

Output:

['a', 'b', 'c', 'd', 'e']
[('b', 'd'), ('a', 'e'), ('b', 'c'), ('a', 'd'), ('a', 'b'), ('a', 'c'), ('c', 'e'), ('c', 'd'), ('b', 'e'), ('d', 'e')]
The

characters are sorted in the tuple by the time they appeared in the input list (not alphabetically, the input list just happens to be in alphabetical order. Shuffling the list doesn't solve the problem, it just hides it). "c" will always appear to the left of "d" and "a" will always appear to the left of everything else.

My solution was to simply replace all tuples with scrambled tuples (shown below). This works, but proves to be very slow, especially on larger lists.

for i in range(len(item_combos)):
    item_combos[i] = tuple(random.sample(item_combos[i], 2))

Is there a faster way to produce similar output?


Correct answer


Selecting random tuples to reverse instead of shuffling each tuple works much faster. This has the same result, since each tuple in item_combos contains only two items.

New tuple "scrambling" code:

for i in range(len(item_combos)):
    if random.random()<.5:
        item_combos[i] = item_combos[i][::-1]

The above is the detailed content of How to efficiently scramble the tuples generated by itertools.combinations()?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete