从列表创建随机对

2024-04-28 22:57:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图创建一个程序来打印列表中的元素对。我需要创建一个字典(一开始是空的),在那里我可以存储值,循环遍历列表以生成一对,并确保没有重复项。

当我在列表中循环时,我需要得到一个随机数,我可以使用它来删除一个元素。 使用pop方法从列表中移除随机选择的元素,将元素存储到一个变量中,比如element1。重复此操作以创建元素2。

通过将element1作为键插入到 对字典,并将其值设置为element2,也就是说,如果我们调用 pairs[element1]稍后它会给我们element2的值。

使用dictionary的items()和keys()方法打印结果。

捕获是,我们唯一允许的函数是来自random模块的random.randrange():

例如:

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

程序的示例运行,这将创建3对,因为列表中有6个元素。

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 = {}

如何改进/添加此代码?


Tags: and方法程序元素列表字典sisterbrother
3条回答
import random

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

pairs = {}

while len(l) > 1:

    #Using the randomly created indices, respective elements are popped out
    r1 = random.randrange(0, len(l))
    elem1 = l.pop(r1)

    r2 = random.randrange(0, len(l))
    elem2 = l.pop(r2)

    # now the selecetd elements are paired in a dictionary 
    pairs[elem1] = elem2

#The variable 'pairs' is now a dictionary of this form:
#{'Sister': 'Aunt', 'Uncle': 'Father', 'Mother': 'Brother'}

##We can now print the elements of the dictionary in your desired format:
i = 1

for key, value in pairs.items():
    print("Pair {}: {} and {}".format(i, key, value))
    i += 1

当你运行它时,你应该看到这样的东西:

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

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

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

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

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

我将为您留下两个练习步骤:

  1. 在开始之前确保列表是唯一的
  2. 确保唯一的列表有偶数个元素(如果没有,请考虑如何操作…)
import random

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

for p in range(len(family) // 2):
    pairs[p+1] = ( family.pop(random.randrange(len(family))),
        family.pop(random.randrange(len(family))) )

print(pairs)

相关问题 更多 >