列表中的唯一值
unique values from a list
如何从下面的列表中获取 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()])
您可以使用 random.sample(donuts, 6)
非常轻松地做到这一点,它将 return 列表中的 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
如何从下面的列表中获取 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()])
您可以使用 random.sample(donuts, 6)
非常轻松地做到这一点,它将 return 列表中的 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