试图让python随机洗牌myclours列表,但希望python只从lis返回4

2024-10-05 14:29:28 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的代码:

def main():
    mycolours = ['R', 'G', 'B', 'Y', 'P', 'O']
    myguess = 'RGBY'
    total_guess = 5
    x = random.shuffle(mycolours[:4])

    for i in range(total_guess):
        if myguess == x:
            print('CORRECT')
        else: 
            print('TRY AGAIN')
main()

它不是从列表中返回4个随机字符串,而是返回值none


Tags: 代码inforifmaindefrangerandom
1条回答
网友
1楼 · 发布于 2024-10-05 14:29:28

您可以通过导入random来洗牌元素,所以让

import random
a = [1,2,3,4,5]

那么你可以说

print random.sample(a,2)

它会打印出来

[4,2]

如果你想要很多随机的数字,那么

z=[]
for i in range(3):
    z.append(random.sample(a,2))

现在z将是这样的

[[3, 4], [1, 3], [7, 6]]

希望这有帮助

相关问题 更多 >