Randomly select another pair of items from a list

The code:

import random

x = ['A','B','C','D','E','F',
     'G','H','I','J','K','L',
     'M','N','O','P','Q','R',
     'S','T','U','V','W','X',
     'Y','Z']

y1 = random.sample(x, 2)
y2 = random.sample(x, 2)
y3 = random.sample(x, 2)
y4 = random.sample(x, 2)
y5 = random.sample(x, 2)

Query

As shown above, I select 5 random combinations of patterns and declare them under variables y'x'.

To improve my code, I would like to do this, but make sure that the element from the list does not appear more than once in all variable outputs, in which all combinations are different and not repeated. I would prefer to achieve this without removing items from the list, as it is reused later in the code.

Expected Result (Example):

>>> y1
['A', 'Q']
>>> y2
['E', 'K']
>>> y3
['C', 'O']
>>> y4
['Z', 'X']
>>> y5
['P', 'L']
+4
source share
6 answers

( , , , ), 2 :

import random

x_copy = x[:]  # copy
random.shuffle(x_copy)
y1 = x[:2]
y2 = x[2:4]
y3 = x[4:6]
y4 = x[6:8]
y5 = x[8:10]

yi s:

x_copy = x[:]  # copy
random.shuffle(x_copy)
y = [x_copy[i*2: (i+1)*2] for i in range(5)]
print(y)
# [['W', 'Z'], ['A', 'Q'], ['B', 'J'], ['O', 'D'], ['X', 'E']]
+4

numpy.random.choice. , (replace=True) (replace=False) ( ):

import numpy as np
x = ['A','B','C','D','E','F',
     'G','H','I','J','K','L',
     'M','N','O','P','Q','R',
     'S','T','U','V','W','X',
     'Y','Z']
np.random.choice(x, size=(5, 2), replace=False)

:

array([['Y', 'Q'],
       ['W', 'R'],
       ['O', 'H'],
       ['Z', 'G'],
       ['L', 'M']], 
      dtype='<U1')

5 , 2.

+2

"" - x :

import random

class SampleCache():
    x = ['A','B','C','D','E','F',
         'G','H','I','J','K','L',
         'M','N','O','P','Q','R',
         'S','T','U','V','W','X',
         'Y','Z']

    def __init__(self):
        self.cache = []

    def get(self):
        _iterations = 0
        while 1:
            sample = random.sample(self.x, 2)
            if not sample in self.cache:
                self.cache.append(sample)
                return sample

            if _iterations > 1000: # just to prevent NOT to run into an infinite loop
                break


s = SampleCache()
for x in range(25):
    print(s.get())
+1

random.sample - , 10 5 :

import random
import string


def random_letters(m=5, n=2):
    letters = random.sample(string.ascii_uppercase, m * n)
    return [letters[n * i:n * (i + 1)] for i in range(m)]

print(random_letters())
# [['I', 'X'], ['J', 'U'], ['O', 'W'], ['G', 'C'], ['D', 'F']]
print(random_letters())
# [['J', 'X'], ['N', 'P'], ['A', 'C'], ['O', 'Z'], ['B', 'H']]
print(random_letters())
# [['U', 'T'], ['J', 'N'], ['C', 'H'], ['D', 'I'], ['K', 'P']]
print(random_letters())
# [['U', 'G'], ['L', 'V'], ['A', 'R'], ['J', 'F'], ['S', 'C']]
print(random_letters())
# [['Y', 'C'], ['R', 'B'], ['E', 'I'], ['S', 'T'], ['H', 'X']]
+1

Use random.sampleto generate a shuffled copy of the source list and generator to get shuffled values โ€‹โ€‹if necessary.

def random_sample(x, n):
    shuffled = random.sample(x, k=len(x))
    for val in range(0, len(x), n):
        yield shuffled[val: val+n]

print([sample for sample in random_sample(x, 2)])

Outputs;

[['I', 'O'], ['V', 'T'], ['U', 'J'], ['L', 'A'], 
 ['E', 'G'], ['Q', 'F'], ['M', 'H'], ['B', 'K'], 
 ['R', 'P'], ['W', 'N'], ['D', 'S'], ['Z', 'Y'], 
 ['X', 'C']]

If you want exactly five random values, use this:

samples = random_sample(x,  2)
five_samples = [next(samples) for _ in range(5)]
print(five_samples)

If you want them one at a time, use

samples = random_sample(x,  2)
print(next(samples))
...
print(next(samples))
0
source

You can loop over the generated pattern and remove elements from x:

x = ['A','B','C','D','E','F',
 'G','H','I','J','K','L',
 'M','N','O','P','Q','R',
 'S','T','U','V','W','X',
 'Y','Z']

new_x = x[:]

import random
final_list = []
for i in range(5):
   the_sample = random.sample(new_x, 2)
   final_list.append(the_sample)
   for b in the_sample:
       new_x.remove(b)

Conclusion:

[['C', 'R'], ['L', 'V'], ['W', 'Y'], ['D', 'O'], ['J', 'Q']]
-1
source

Source: https://habr.com/ru/post/1681703/


All Articles