Python 如何打印从列表中随机选择的内容?
如果我使用Python 如何打印从列表中随机选择的内容?,python,random,Python,Random,如果我使用print(random.sample(My_List,k=2))Python从我的列表中随机选择两件事 我如何告诉Python打印它为我挑选的两个随机对象中的一个 例如: print("My personal favorite from those two would be ..." 如何打印从列表中随机选择的内容?一行: print(f"My personal favorite from those two would be ... {random.choice(random.s
print(random.sample(My_List,k=2))
Python从我的列表中随机选择两件事
我如何告诉Python打印它为我挑选的两个随机对象中的一个
例如:
print("My personal favorite from those two would be ..."
如何打印从列表中随机选择的内容?一行:
print(f"My personal favorite from those two would be ... {random.choice(random.sample(My_List, k=2))}")
将其分配给变量,然后使用串联
myList = ['red', 'blue', 'green', 'white', 'black', 'orange']
x=random.sample(myList, k=2)
print('My favorite color is ' + x[1])
输出:
My favorite color is blue
如果您想从随机样本中随机选取一些内容,请包括random.choice:
print('My favorite color is ' + random.choice(x))
打印前将其分配给一个变量您可以使用
random.choice()
。不,两者都不正确,我只是说如何让python从我的列表中随机选择一个项目。使用这种解决方案,您不需要示例
。同意。只是回答问题。我试过这么做,但仍然不起作用,我的列表中有七个项目,我已经设置好让它从列表中随机选择两个项目,我试过你的代码,它确实从列表中给了我一个随机项目,但不是从python随机给我的输出中。这并不是我想要的,这只是向我展示了如何让python从我的列表中随机选择一些东西,我不知道你的意思。这让Python从列表中进行选择,将选择分配给一个新列表,然后通过(a)显式调用它,或(b)Python随机选择一个元素来打印列表中的一个元素。你在找什么?我想我错过了什么。