Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Random Slice Idiom

Is there a pythonic way to slice a sequence type such that the returned slice is of random length and in random order? For example, something like:

>>> l=["a","b","c","d","e"]
>>> rs=l[*:*]
>>> rs
['e','c']
like image 871
AJ. Avatar asked May 29 '11 16:05

AJ.


People also ask

What is meant by slicing in Python?

Slicing in Python is a feature that enables accessing parts of sequences like strings, tuples, and lists. You can also use them to modify or delete the items of mutable sequences such as lists. Slices can also be applied on third-party objects like NumPy arrays, as well as Pandas series and data frames.

How do you randomly sample data points in Python?

You can use random. randint() and random. randrange() to generate the random numbers, but it can repeat the numbers. To create a list of unique random numbers, we need to use the sample() method.

How do you select two random elements in a list 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.

What is sequence slicing?

You can slice sequences to create new sequences of the same type containing subsets of the original elements. Slice operations can modify mutable sequences—those that do not modify a sequence work identically for lists, tuples and strings.


2 Answers

How about...

random.sample(l, random.randint(1, len(l)))

Quick link to docs for the random module can be found here.

like image 98
Andrew White Avatar answered Oct 21 '22 10:10

Andrew White


No idiom that I'm aware of, but random.sample does what you need.

>>> from random import sample, randint
>>> 
>>> def random_sample(seq):
...     return sample(seq, randint(0, len(seq)))
... 
>>> a = range(0,10)
>>> random_sample(a)
[]
>>> random_sample(a)
[4, 3, 9, 6, 7, 1, 0]
>>> random_sample(a)
[2, 8, 0, 4, 3, 6, 9, 1, 5, 7]
like image 28
Simon Whitaker Avatar answered Oct 21 '22 10:10

Simon Whitaker