How to get a random snippet of python constant list. (smallest code)

Hi, I have a list of 100 items, now I want a piece of 6 items to be selected randomly. Any way to do this in a simple simple concise statement ???

This is what I came up with (but it will be retrieved sequentially)

mylist #100 items N=100 L=6 start=random.randint(0,NL); mylist[start:start+L] 
+4
source share
1 answer

You can use the shuffle() method in the list before the slice.

If the order of the list matters, just make a copy of it and cut it 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 can also use len () instead of specifying the length of the list.

hit>

As shown below in THC4K, you can use the random.sample () method, for example below IF , which you need is a set of random numbers from the list (this is how I read your question).

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

This is much more complicated than my first attempt!

+7
source

All Articles