简体   繁体   中英

Python: More efficient way to get random slices from several lists

Here's a piece of python code I wrote to get random characters from 4 lists and append them to a separate list:

key.append(chr(upper[randint(0,len(upper)-1)]))
key.append(chr(lower[randint(0,len(lower)-1)]))
key.append(chr(nums[randint(0,len(nums)-1)]))
key.append(chr(symbols[randint(0,len(symbols)-1)]))

Is there a more elegant way to do this?

I'd recommend using random.choice + list.extend :

lsts = [upper, lower, nums, symbols]    
key.extend(chr(random.choice(x)) for x in lsts)

random.choice( seq )

Return a random element from the non-empty sequence seq . If seq is empty, raises IndexError .

source

key.append(chr(random.choice(upper)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM