Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python3.x中使用random打印不同的值_Python_Python 3.x_Random - Fatal编程技术网

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

在Python3.x中使用random打印不同的值,python,python-3.x,random,Python,Python 3.x,Random,这个代码给了我4个值,这是可以的,但我不想有重复。所以,若程序采用例如“白色”,它将不包括在迭代中。有什么想法吗?如果你有4个值,你只想随机排列它们,只需使用random.shuffle: from random import randint result = [] colors = {1: "Red", 2: "Green", 3: "Blue", 4: "White"} while True: for key in colors: ball = randint(1

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

如果你有4个值,你只想随机排列它们,只需使用
random.shuffle

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)
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 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)
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)

您可以检查是否已获取该特定值。

from random import sample

colors = {1: "Red", 2: "Green", 3: "Blue", 4: "White"}

result = [ball/10 for ball in sample(colors, 4)]

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


希望这有帮助

查看
random.shuffle
循环毫无意义;我不清楚你想做什么,你迭代
颜色
,但从不使用
,如果你有一个更大的列表,并且你需要从中绘制
n
元素,而不需要替换,你只需洗乱列表,然后获取
draw=big\u list[:n]
@l3via比
示例更好case@Hiddenguy您需要指定样本大小,在尝试新函数时阅读文档