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
Post a Comment