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

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

PHPz
Release: 2024-02-22 12:43:11
forward
688 people have browsed it

如何有效地打乱 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)
Copy after login

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')]
Copy after login
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))
Copy after login

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]
Copy after login

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!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template