I have two lists x and y, both of length n, with xi and yi forming a pair. How could I take a random sample of m values from these two lists while preserving the pairing information (e.g. x[10] and y[10] would be together in the resulting sample)
My initial idea is this.
And the code would look something like this.
templist = list()
for tup in zip(x, y):
templist.append(tup)
random.shuffle(templist)
x_sub = [a for a, b in templist[0:m]]
y_sub = [b for a, b in templist[0:m]]
This seems rather kludgy to me. Is there any way I could make this more clear, concise, or Pythonic?
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.
1 Answer. The syntax is: random. sample(list,k) where k represents, number of values to be sampled.
The sample() is an inbuilt method of the random module which takes the sequence and number of selections as arguments and returns a particular length list of items chosen from the sequence i.e. list, tuple, string or set. It is used for random selection from a list of items without any replacement.
One simple and popular way to merge(join) two lists in Python is using the in-built append() method of python. The append() method in python adds a single item to the existing list. It doesn't return a new list of items. Instead, it modifies the original list by adding the item to the end of the list.
You can sample m pairs and split those into two lists with the following code:
import random
x = list(range(1, 10))
y = list("abcdefghij")
m = 3
x_sub, y_sub = zip(*random.sample(list(zip(x, y)), m))
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