Sana ullah
Sana ullah

Reputation: 21

Is there anyway to get random indexes of a list in a new list in python

I am trying to get indexes of a list store into a new list. for example,

A = ['A', 'B', 'C',....,'Z']

and B list will select random no of indexes of A list like.

B = [[2,None,None], [1,None,None], [3,None,None],.....,[0, None,None]]

where list limit is, suppose, 10 and None will be replaced with the random no between 0 to 20 and finally the list of resultant look like,

result = [[2, 2, 3], [0, 4, 5], [8, 2, 4], [3, 8, 9]]

the first element in a sublist refers to the list A and the 2nd and third elements refer to the random selection of numbers between 0 to 10

Upvotes: 0

Views: 81

Answers (3)

user12734636
user12734636

Reputation:

Think this basis for you

A = ['A', 'B', 'C','Z']
B = [[2,None,None], [1,None,None], [3,None,None],[0, None,None]]
for newb in B:
    if  newb[1] is None:
        newb[1] = random.randrange(0,10)
    if newb[2] is None:
        newb[2] = random.randrange(0,10)
print(B)

it do like

[[2, 2, 2], [1, 6, 9], [3, 5, 7], [0, 6, 2]]

Upvotes: 1

Nick
Nick

Reputation: 147196

If you don't mind possible replication of values in the elements you can use a list comprehension, using random.randrange to generate the numbers:

result = [[random.randrange(26), random.randrange(10), random.randrange(10)] for _ in range(10)]
print(result)

Sample output:

[[18, 8, 1], [24, 1, 4], [24, 6, 5], [1, 4, 4], [7, 0, 9], [10, 7, 7], [0, 6, 9], [0, 9, 4], [6, 4, 4], [4, 2, 7]]

If you want to ensure no replication in each of elements of the list, you can use zip and random.sample to put together 3 lists of unique values and select values from those:

result = [[a, b, c] for a, b, c in zip(random.sample(range(26), 10), random.sample(range(10), 10), random.sample(range(10), 10))]
print(result)

Sample output:

[[2, 0, 1], [21, 4, 0], [11, 1, 4], [10, 7, 5], [15, 3, 3], [23, 6, 8], [25, 5, 2], [1, 9, 7], [24, 8, 9], [6, 2, 6]]

Upvotes: 1

Shibiraj
Shibiraj

Reputation: 769

Using random.sample.

import random
result = [random.sample(range(len(A)), 1) + random.sample(range(10), 2) for _ in range(10) ]

Upvotes: 2

Related Questions