列表中的唯一值

时间:2015-05-05 12:51:30

标签: list python-3.x unique

如何从下面的列表中获得6个唯一值?

# List of donuts
Donuts = ['Apple Cinnamon',
         'Strawberry","Custard',
         'Sugar Ring',
         'Chocolate Caramel',
         'Lemon Circle',
         'Blueberry Blaster',
         'Strawberry Surprise',
         'Simple Sugar']

这是我到目前为止所做的:

# Function - Random Selection of Donuts
def Generate_Random():
    if (len(Donuts)>0):
        choice.set(randint(0, len(Donuts)-1))
        stvRandomChoice.set (Donuts[choice.get()])

1 个答案:

答案 0 :(得分:0)

您可以使用random.sample(donuts, 6)轻松完成此操作,这将从列表中返回6个随机元素的列表。

有关详细信息,请参阅https://docs.python.org/3/library/random.html

修改:为了清晰起见,已实施:

import random

# List of donuts
Donuts = ['Apple Cinnamon',
          'Strawberry',
          'Custard',
          'Sugar Ring',
          'Chocolate Caramel',
          'Lemon Circle',
          'Blueberry Blaster',
          'Strawberry Surprise',
          'Simple Sugar']

# Function - Random Selection of Donuts
def Generate_Random(list, num):
    return random.sample(list, num)

# Print out randomly selected donuts using the above function
for element in Generate_Random(Donuts, 6):
    print element