代码之家  ›  专栏  ›  技术社区  ›  Hiddenguy

在Python3.x中使用random打印不同的值

  •  4
  • Hiddenguy  · 技术社区  · 6 年前
    from random import randint
    
    result = []
    colors = {1: "Red", 2: "Green", 3: "Blue", 4: "White"}
    
    while True:
        for key in colors:
            ball = randint(1,4)
            probability = (ball/10)
            result.append(probability)
    
        break
    
    print(result)
    

    这个代码给了我4个值,这是可以的,但我不想有重复。所以,若程序采用例如“白色”,它将不包括在迭代中。有什么想法吗?

    2 回复  |  直到 6 年前
        1
  •  2
  •   L3viathan gboffi    6 年前

    random.shuffle :

    from random import shuffle
    
    colors = {1: "Red", 2: "Green", 3: "Blue", 4: "White"}
    
    balls = list(colors)
    shuffle(balls)
    result = [ball/10 for ball in balls]
    
    print(result)
    

    另一个选项(尤其适用于较大的列表,因为无序排列列表“很慢”)是使用 random.sample :

    from random import sample
    
    colors = {1: "Red", 2: "Green", 3: "Blue", 4: "White"}
    
    result = [ball/10 for ball in sample(colors, 4)]
    
    print(result)
    
        2
  •  0
  •   L3viathan gboffi    6 年前


    list_taken = []
    number = randint(1,n)
    while number in list_taken:
        number = randint(1,n)
    list_taken.append(number)
    

    因此,上述4行代码所做的是,维护一个已获取值的列表,并重复查找新值,直到得到一个新值。