简体   繁体   English

在python 3.x中随机打印不同的值

[英]Print different values with random in python 3.x

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)

This code gives me 4 values which is ok, but I'd like to have no repetitions. 这段代码给了我4个值,这是好的,但我不想重复。 So if program took eg "White", it won't include it to iteration. 因此,如果程序采用例如“白色”,则不会将其包含在迭代中。 Any ideas? 有任何想法吗?

If you have 4 values and you just want a random permutation of them, just use random.shuffle : 如果你有4个值而你只想随机排列它们,只需使用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)

Another option (especially good with larger lists, because shuffling a list is "slow") is the use of random.sample : 另一个选项(特别是对于较大的列表,因为混乱列表是“慢”)是使用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)

You can check whether that particular value has been taken or not. 您可以检查是否已采用该特定值。

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

So what above 4 lines of code do is, maintain a list of already taken values and repeat finding new values until it gets a new one. 因此,以上4行代码的作用是,维护已经采用的值列表并重复查找新值,直到获得新值。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM