代码之家  ›  专栏  ›  技术社区  ›  Pavi Thran

如何在python中使用随机函数?

  •  -2
  • Pavi Thran  · 技术社区  · 8 年前
    #program to tic-tac-toe
    from random import *
    num=[i for i in range(1,10)]
    flag=0
    ulist=list();
    xlist=list();
    olist=list();
    count=0
    while(count < 9):
      if(flag==0):
        x=random.choice(num)
        if(x not in ulist):
          ulist.append(x)
          xlist.append(x)
          flag=1
      if(flag==1):
        o=random.choice(num)
        if(o not in ulist):
            ulist.append(o)
            olist.append(o)
            flag=0
      count+=1
    
    print (ulist)
    print (xlist)
    print (olist)
    

    这是我的代码,我调用了随机函数,但它仍然表示我没有使用随机函数

    2 回复  |  直到 8 年前
        1
  •  0
  •   bigbounty    8 年前

    随机函数的正确使用:

    对于连续数字,randint或randrange可能是最佳选择,但如果序列(即列表)中有多个不同的值,也可以使用选项:

    >>> import random
    >>> values = list(range(10))
    >>> random.choice(values)
    5
    

    选择也适用于非连续样本中的一个项目:

    >>> values = [1, 2, 3, 5, 7, 10]
    >>> random.choice(values)
    7
    

    如果你需要它“加密性强”,还有一个秘密。python 3.6及更新版本中的选项:

    >>> import secrets
    >>> values = list(range(10))
    >>> secrets.choice(values)
    2
    
        2
  •  0
  •   BoarGules    8 年前
    from random import *
    

    与不兼容

    random.choice()
    

    要么这样做

    import random
    ...
    random.choice()
    

    from random import *
    ....
    choice()
    
    推荐文章