Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get random slice of python list of constant size. (smallest code)

Tags:

python

Hi I have a List say 100 items, now i want a slice of say 6 items which should be randomly selected. Any way to do it in very simple simple concise statement???

This is what i came up with (but it will fetch in sequence)

 mylist #100 items
 N=100
 L=6
 start=random.randint(0,N-L);
 mylist[start:start+L]
like image 397
Markandey Singh Avatar asked Sep 25 '10 12:09

Markandey Singh


People also ask

How do you randomly select from a list in Python?

Use the random.sample() function when you want to choose multiple random items from a list without repetition or duplicates. There is a difference between choice() and choices() . The choices() was added in Python 3.6 to choose n elements from the list randomly, but this function can repeat items.

How do you randomly select 5 items from a list in Python?

Select randomly n elements from a list using choice() The choice() method is used to return a random number from given sequence. The sequence can be a list or a tuple. This returns a single value from available data that considers duplicate values in the sequence(list).

How do I make a list of specific size in Python?

We can initialize a list of size n using a range() statement. The difference between using a range() statement and the None method is that a range() statement will create a list of values between two numbers. By default, range() creates a list from 0 to a particular value.

How do I create a fixed size list in Python?

You can use this: [None] * 10 . But this won't be "fixed size" you can still append, remove ... This is how lists are made. You could make it a tuple ( tuple([None] * 10) ) to fix its width, but again, you won't be able to change it (not in all cases, only if the items stored are mutable).


1 Answers

You could use the shuffle() method on the list before you slice.

If the order of the list matters, just make a copy of it first and slice out of the copy.


mylist #100 items
shuffleList = mylist
L=6
shuffle(shuffleList) 
start=random.randint(0,len(shuffleList)-L);
shuffleList[start:start+L]

As above, you could also use len() instead of defining the length of the list.

As THC4K suggested below, you could use the random.sample() method like below IF you want a set of random numbers from the list (which is how I read your question).

mylist #100 items
L=6
random.sample(mylist, L)

That's a lot tidier than my first try at it!

like image 101
Azz Avatar answered Nov 14 '22 23:11

Azz