简体   繁体   中英

How to create random pairs from list

I am trying to create 8 random pairs from a list of from given 10 images.

import random 
imageList = ['1.jpg','2.jpg','3.jpg','4.jpg','5.jpg','6.jpg','7.jpg','8.jpg','9.jpg','10.jpg']

for i in range(len(imageList)):
    imagepair = range(len(imageList) - 1)

You can simply shuffle the list, then take the first 4 items from it, and repeat once more:

for _ in range(2):
    random.shuffle(imageList)
    i=0
    while(i<8):
        print(imageList[i], imageList[i+1])
        i+=2

use random function to get 2 integers as index values and pair the corresponding image.

You can use random.shuffle and create a generator to get samples of image groups as many times as needed.

def image_generator(l):
    while True:
        random.shuffle(l)
        yield l[:2]
        
for i in range(8):
    print(next(image_generator(imageList)))
['6.jpg', '2.jpg']
['10.jpg', '5.jpg']
['8.jpg', '6.jpg']
['6.jpg', '1.jpg']
['5.jpg', '3.jpg']
['8.jpg', '6.jpg']
['6.jpg', '2.jpg']
['8.jpg', '2.jpg']

Another way is you can use itertools.product to get permutations of n (or 2) for images, filtering out cases where both images are the same. And then you can use random.sample to get 8 samples.

import random
import itertools

def image_generator(iterable, groups, samplesize):
    grouped = (i for i in itertools.product(imageList,repeat=2) if i[0]!=i[1])
    return random.sample(list(grouped), samplesize)

image_generator(imageList, 2, 8)
[('8.jpg', '7.jpg'),
 ('7.jpg', '10.jpg'),
 ('7.jpg', '2.jpg'),
 ('6.jpg', '7.jpg'),
 ('5.jpg', '3.jpg'),
 ('2.jpg', '1.jpg'),
 ('10.jpg', '5.jpg'),
 ('9.jpg', '10.jpg')]

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