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


hi have list 100 items, want slice of 6 items should randomly selected. way in simple simple concise statement???

this came (but fetch in sequence)

 mylist #100 items  n=100  l=6  start=random.randint(0,n-l);  mylist[start:start+l] 

you use shuffle() method on list before slice.

if order of list matters, make copy of first , slice out of copy.


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

as above, use len() instead of defining length of list.

as thc4k suggested below, use random.sample() method below if want set of random numbers list (which how read question).

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

that's lot tidier first try @ it!


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -