列表中随机项的索引

时间:2018-03-12 13:26:28

标签: python python-3.x

我有以下列表:

cnames = [" green ", " blue ", " yellow ", " gray ", " pink ", " orange ", "purple ", " red ", "brown "]

如何获得6个随机且唯一的索引,表示0和之间的数字     该列表中的len(cnames)

1 个答案:

答案 0 :(得分:2)

随机模块应该有帮助。

import random
random.sample(cnames, 6)   #random.sample returns unique list of random choice. 

random.sample(range(len(cnames)), 6)#to get random int representing a number between 0 and len(cnames)

<强>输出:

[' gray ', ' pink ', 'purple ', ' blue ', ' orange ', ' green ']