iKnowher
iKnowher

Reputation: 23

how to generate a random choice when i have a list of 2 dimensional?

If a list like this :L = [(1, 2), (2, 2), (3, 0)] where i want to random choice an element of L, it returns an Error saying the element of L must be 1-dimensional. So, how should i use random.choice when the elements are not 1-dimensional?

import numpy as np
L = [(1, 2), (2, 2), (3, 0)]
re = np.random.choice(L)

when i try code above, it reports wrong

Upvotes: 1

Views: 571

Answers (2)

James Bear
James Bear

Reputation: 444

numpy is a matrix library so it confused L with a 2D array. Use builtin random module instead:

import random
L = [(1, 2), (2, 2), (3, 0)]
re = random.choice(L)

Upvotes: 0

Daniel
Daniel

Reputation: 81

A simple solution to this is to take a random index of the list, instead of the element itself:

import numpy as np
L = [(1, 2), (2, 2), (3, 0)]
random_index = np.random.choice(len(L))
re = L[random_index]

Upvotes: 1

Related Questions