简体   繁体   English

Python:从多个列表中获取随机切片的更有效方法

[英]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:这是我编写的一段 python 代码,用于从 4 个列表中获取随机字符并将它们附加到一个单独的列表中:

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 :我建议使用random.choice + list.extend

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

random.choice( seq ) random.choice( seq )

Return a random element from the non-empty sequence seq .从非空序列seq返回一个随机元素。 If seq is empty, raises IndexError .如果seq为空,则引发IndexError

source 来源

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python:在两个列表之间匹配字符串切片的有效方法 - Python: Efficient way of matching slices of strings between two lists python列表中的pandas数据框以更有效的方式 - pandas data frame from python lists in more efficient way 在python中删除多个列表中的几个项目的最有效方法? - Most efficient way to remove several items in several lists in python? 在 python 中处理大列表的更有效方法? - More efficient way to handle big lists in python? 从列表或元组列表中选择随机对象的哪种方法更有效? - Which is the more efficient way to choose a random pair of objects from a list of lists or tuples? 从不同长度的多个列表中获取随机整数的更有效和通用的方法 - More efficient and general way of getting a random integer from multiple lists of different lengths 在Python中获取几个元组列表的第二个元素的简单有效方法? - Easy & efficient way to get intersection of the 2nd elements for several lists of tuples in Python? 从Python dict获得独特的第一次出现的更有效方法 - More efficient way to get unique first occurrence from a Python dict Python Selenium 添加多个用户的更有效方法 - Python Selenium More Efficient Way of Adding Several Users 需要一种更有效的方法来从数据库中检索多个日期系列 - Need more efficient way to retrieve several dated series from a DB
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM