Hack Forums
[Python] How to make random pairs of elements in a list? - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [Python] How to make random pairs of elements in a list? (/showthread.php?tid=5954459)



How to make random pairs of elements in a list? - E V O - Mar 28, 2019

I'm trying to randomly pair two elements from a list. The list contains more lists as elements. The random pair serves as input for a function. What would be the best approach to make this pairing as random as possible? In the end I want to iterate the process.


RE: How to make random pairs of elements in a list? - datguy.dev - Mar 28, 2019

(Mar 28, 2019 04:06 PM)E V O Wrote:  I'm trying to randomly pair two elements from a list. The list contains more lists as elements. The random pair serves as input for a function. What would be the best approach to make this pairing as random as possible? In the end I want to iterate the process.

Can't really without the application. Are you expecting any element of a list, and nested lists, to be viable for all arguments of the function? You could extrapolate on:

Code
seed = randrange(randrange(randrange(0, len(some_list_with_lists) ), len(some_list_with_lists)*2), len(some_list_with_lists)*3)



RE: How to make random pairs of elements in a list? - AeroBlue - Mar 28, 2019

I would look into itertools and random

Idk if this is what you are looking for but I made this:

Code
list1= ["1","2","3"],["a","b","c"],["x","y","z"],["4","5","6"]
def pair(list, r):
return list(itertools.combinations(list_, r))

combinations = pair(list, 2)
random.choice(combinations)
Code
Output:(['a', 'b', 'c'], ['4', '5', '6'])

If you wanted to not iterate through the combination again you could do something like this:
Code
combination = random.choice(combinations)
combinations.remove(combination)



RE: How to make random pairs of elements in a list? - Dark - Mar 28, 2019

Just use the random package....