Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random sample of paired lists in Python

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.

  • use zip to create a list of tuples
  • shuffle the list of tuples
  • select the first m tuples from the list
  • break up the tuples into new paired lists

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?

like image 392
Daniel Standage Avatar asked Sep 15 '15 02:09

Daniel Standage


People also ask

How do you randomly sample a list in Python?

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.

How do I randomly select two lists in Python?

1 Answer. The syntax is: random. sample(list,k) where k represents, number of values to be sampled.

How do you select random names from a list without repetition in Python?

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.

How do you combine lists in Python?

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.


1 Answers

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))
like image 160
Jerry Day Avatar answered Oct 03 '22 22:10

Jerry Day