I'm attempting to create a sample of myList
with the exception of i_
.
My Attempt:
i_ = 'd'
myList = ['a','b','c','d','e']
myList = random.sample(myList, 3)
Although the above sample works fine, there is still a chance that i_
is removed from myList
.
I would like to create a sample without the value of i_
being removed.
Desired Output:
Any list output containing 3 items including i_
, e.g:
['a','d','e']
In Python, you can randomly sample elements from a list with choice() , sample() , and choices() of the random module. These functions can also be applied to a string and tuple. choice() returns one random element, and sample() and choices() return a list of multiple random elements.
In simple terms, for example, you have a list of 100 names, and you want to choose ten names randomly from it without repeating names, then you must use random. sample() . Note: Use the random. choice() function if you want to choose only a single item from the list.
Use the randint() function(Returns a random number within the specified range) of the random module, to generate a random number in the range in specified range i.e, from 1 to 100.
The simplest way to use Python to select a single random element from a list in Python is to use the random. choice() function. The function takes a single parameter – a sequence. In this case, our sequence will be a list, though we could also use a tuple.
Just sample 2 values from the list without the i_
and insert i_
later:
new_list = random.sample([i for i in myList if i != i_], 2)
new_list.insert(random.randrange(0, 3), i_)
But this assumes that i_
occurs only once in your list - seems reasonable given your example but I wanted to mention this for completeness. Also I'm not sure what the desired result should be if there were multiple i_
in the list.
You could also use a hit&miss approach that generates a sample until you get one that contains i_
:
new_list = []
while i_ not in new_list:
new_list = random.sample(myList, 3)
Note that this could be really slow if it's unlikely that i_
is drawn in the sample. For a 3-sample of 5 elements it's quite fast but it could be really slow if you draw a 3-sample from 1000 elements.
Guarantee that i_
will be in the list, then take one fewer random element.
myList.remove(i_)
myList = random.sample(myList, 2)
myList.append(i_)
You can combine these into one line if you wish.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With