从列表创建随机对 [英] Creating random pairs from lists

查看:58
本文介绍了从列表创建随机对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个程序,该程序将打印列表中的成对元素.我需要创建一个字典(起初是空的),可以在其中存储值,在列表中循环以成对,并确保没有重复.

I am trying to create a program that will print pairs of the elements in a list. I need to create a dictionary (that is empty at first) where I can store values, Loop through the list to make a pair and make sure there are no duplicates.

当我在列表中循环时,我需要获取一个随机数,并且可以使用它来删除元素. 使用pop方法从列表中删除随机选择的元素,然后将该元素存储到变量中,例如element1.重复它以创建element2.

When I loop in the list, I need to get a random number and I can use it to remove an element. Remove the randomly selected element from the list using pop method, store the element to a variable, say element1. Repeat it to create element2.

通过将element1作为键插入到元素1来将element1映射到element2. 对字典,并将其值设置为element2,即如果我们调用 Pairs [element1]之后,应该为我们提供element2的值.

Map the element1 to element2 by inserting the element1 as key to the pairs dictionary, and setting its value to element2, that is, if we call pairs[element1] later it should give us the value of element2.

使用字典的items()和keys()方法打印结果.

Print the result using dictionary’s items() and keys() methods.

问题是,我们唯一允许的功能是 random 模块中的random.randrange():(

The catch is, the only function we are allowed is the random.randrange()from the random module :(

示例是这样:

list = ["Mother", "Father", "Aunt", "Uncle", "Brother", "Sister" ]

该程序的示例运行,由于列表中有6个元素,因此将创建3对.

Sample run of the program, this creates 3 pairs because there are 6 elements in the list.

Pair 1: Mother and Aunt
Pair 2: Uncle and Sister 
Pair 3: Brother and Father

这是我现在的程序:

family = ["Mother", "Father", "Aunt", "Uncle", "Brother", "Sister" ]

for x in family:


pairs = {}

如何改进/添加此代码?

How can I improve/add to this code?

推荐答案

使用random.randrange从列表中选择(并删除)随机元素很容易:

Using random.randrange to select (and remove) a random element from a list is easy:

def pop_random(lst):
    idx = random.randrange(0, len(lst))
    return lst.pop(idx)

现在,假设列表中有偶数个元素,我们可以很容易地建立配对:

Now, assuming that the list has an even number of elements, we can build pairs very easily:

pairs = []
while lst:
    rand1 = pop_random(lst)
    rand2 = pop_random(lst)
    pair = rand1, rand2
    pairs.append(pair)

作为练习,我遗漏了2个步骤:

There are 2 steps missing that I'll leave as an exercise for you:

  1. 开始之前,请确保列表是唯一的
  2. 确保唯一列表具有偶数个元素(并弄清楚如果不存在该怎么办...)

这篇关于从列表创建随机对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆