Home > OS >  Creating a list from 2 lists' elements selected randomly in Python
Creating a list from 2 lists' elements selected randomly in Python

Time:04-11

I have a list of tuples, and inside that tuple, I have 2 lists. It looks something like the following:

value=[(['55', '56', '57', '58', '2'], ['59', '60', '61', '62', '2']), (['63', '64', '65', '66', '2'], ['51', '52', '53', '54', '2'])]

From each tuple's 2 lists, I want to create a list which will also have the same length, (in this above example, of length 5), and I want to do this for each tuple in the outer list. For example, with the above example, the first value of the first final list will be either 55 or 59, the 2nd value of the final list will be either from 56 or 60, and so on.

One possible outcome will be:

['59', '60', '57', '58', '2'] and ['63', '52', '53', '66', '2']

How can I do it?

CodePudding user response:

You can use zip() with the unpacking operator to get the choices for each position in a sublist, and then use a list comprehension to perform this operation for every tuple in your original list. Notably, the use of unpacking makes this operation extensible if you have a variable number of lists inside each tuple:

import random
[[random.choice(choices) for choices in zip(*item)] for item in value]

With the given data, you'll get an output like:

[['55', '60', '61', '62', '2'], ['51', '52', '65', '66', '2']]

CodePudding user response:

Each tuple inside values contains two lists. The first list has index 0, the second list has index 1.

We can use random.randint(0, 1) to generate a binary choice, either 0 or 1, which is going to be the index of the list to where we pick the element.

import random
res = [[v[random.randint(0, 1)][k] for k in range(len(v[0]))] for v in value]

Let's break down the list-comprehension syntax:

  • First, we loop over the tuples contained in value with for v in value.
  • Then, with for k in range(len(v[0])) we loop over the number of elements of the first list of each tuple (first or second doesn't matter here, as both lists have the same number of elements).
  • Then, with v[random.randint(0, 1)][k] we are randomly picking the first or second list, and from this list we extract the k-th value.
  • Related