简体   繁体   English

在 python 中创建随机字典

[英]Creating a random dictionary in python

I would like to create a random dictionary starting from the following array:我想从以下数组开始创建一个随机字典:

list = [1,2,3,4,5]

In particular, I would like to have as keys of the dictionary all the elements of the array and as corresponding keys, randomly pick some values from that array except the value that corresponds to the key特别是,我希望将数组的所有元素作为字典的键,并作为相应的键,从该数组中随机选择一些值,除了对应于键的值

An example of expected output should be something like:预期 output 的示例应类似于:

Randomdict = {1: [2, 4], 2: [1,3,5] 3: [2] 4: [2,3,5] 5: [1,2,3,4]}

And last but not least all keys should have at least 1 value最后但并非最不重要的一点是,所有键都应该至少有 1 个值

It can be done with the random module and comprehensions:它可以通过random模块和理解来完成:

from random import sample, randrange

d = {i: sample([j for j in lst if i != j], randrange(1, len(lst) - 1))
     for i in lst}

If you first use random.seed(0) for reproducible data, you will get:如果您首先将random.seed(0)用于可重现的数据,您将获得:

{1: [3, 2], 2: [4, 3], 3: [2, 4], 4: [3, 1]}
{1: [3], 2: [1], 3: [4, 1], 4: [1, 3]}
{1: [3, 2], 2: [3, 4], 3: [4], 4: [2, 3]}

Something like this?像这样的东西? Might needs some tweaks可能需要一些调整

from random import randrange, sample

q = [1, 2, 3, 4, 5]
a = {}
for i in q:
    n = randrange(len(q)-1)
    a[i] = sample(q, n)

print(a)

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

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