python - Removing random items from a list -
so have 10 txt files(named a_1,a_2........a_10), want randomly select 3 files out of these 10 in way, when 3 files randomly chosen, removed original list , new list can created using randomly chosen 3 files.i tried following method, when try command print(filelist), still shows 10 txt files,any suggestion or advice helpful.
import random filelist=[] in list(range(1,11)): filelist.append("/users/hrihaan/desktop/a_%s.txt" %i) newlist=random.sample(filelist,4)
if order of elements in filelist
don't matter you, can:
shuffle filelist
take first n
elements new_list
, , reassign remaining elements filelist
in [48]: import random rn in [49]: filelist = range(10) in [50]: rn.shuffle(filelist) in [51]: new_list = filelist[:3] in [52]: filelist = filelist[3:] in [53]: new_list out[53]: [3, 4, 5] in [54]: filelist out[54]: [9, 8, 7, 6, 1, 2, 0]
Comments
Post a Comment