gpt4 book ai didi

python - 如何生成具有指定数量的键和每个键随机数量的值的字典?

转载 作者:行者123 更新时间:2023-12-01 02:59:21 24 4
gpt4 key购买 nike

假设我将键的数量指定为 5(以便键为 0、1、2、3 和 4 等),并且我希望每个键的值的数量是随机的,其中每个值都是 0 、1、2、3 或 4,每个键中没有重复值。我正在尝试制作一个随机完整图表(如果这对您有意义的话)。输出示例:

dict = { "0": ["3"],
"1": ["4"],
"2": ["3","4"],
"3": ["0","2"],
"4": ["1","2"]
}

最佳答案

import random

number_of_nodes = 5
graph = dict()

for i in range(number_of_nodes):
graph[i] = random.sample(range(0, number_of_nodes), random.randint(0, number_of_nodes))

关于python - 如何生成具有指定数量的键和每个键随机数量的值的字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43960369/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com