[英]Randomly select elements in a nested list one time
Is there an algorithmic way that I could "randomly" select elements in a nested list, but not make a repeated selection?有没有一种算法方法可以“随机”选择嵌套列表中的元素,但不能重复选择? I am trying to figure out a way to randomly select elements in the nested list only once until all elements have been selected.我试图找出一种方法,只随机选择嵌套列表中的元素一次,直到选择了所有元素。
This is my nested list:这是我的嵌套列表:
devices = [['radio/36'],
['radio/38',
'radio/31'],
['radio/21',
'radio/29'],
['radio/25',
'radio/9',
'radio/6'],
['radio/13',
'radio/14',
'radio/30'],
['radio/19',
'radio/8',
'radio/26',
'radio/24'],
['radio/34',
'radio/11',
'radio/27',
'radio/20',
'radio/23'],
['radio/15',
'radio/37',
'radio/39',
'radio/10']]
For example there is nothing in the code below that will prevent selecting or printing something twice.例如,下面的代码中没有任何内容可以阻止选择或打印两次内容。
import random
for i in range(len(devices)):
random_pick = devices[random.randint(0, len(devices))]
print(random_pick)
The code above is definitely lacking a lot and has the potential to print something twice or completely miss an element.上面的代码肯定缺乏很多,并且有可能打印两次或完全错过一个元素。
['radio/19', 'radio/8', 'radio/26', 'radio/24']
['radio/38', 'radio/31']
['radio/19', 'radio/8', 'radio/26', 'radio/24']
['radio/36']
['radio/36']
['radio/15', 'radio/37', 'radio/39', 'radio/10']
['radio/36']
['radio/36']
TL;DR - What @Barmar said in the comments TL; DR - @Barmar 在评论中所说的话
Using random.shuffle
would be a pretty simple way of iterating through your list in a random order.使用random.shuffle
将是一种以随机顺序遍历列表的非常简单的方法。
import random
def main():
devices = [
['radio/36'],
['radio/38', 'radio/31'],
['radio/21', 'radio/29'],
['radio/25', 'radio/9', 'radio/6'],
['radio/13', 'radio/14', 'radio/30'],
['radio/19', 'radio/8', 'radio/26', 'radio/24'],
['radio/34', 'radio/11', 'radio/27', 'radio/20', 'radio/23'],
['radio/15', 'radio/37', 'radio/39', 'radio/10']
]
random.shuffle(devices)
for device in devices:
print(device)
if __name__ == '__main__':
main()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.