我正在尝试创建一个程序,用于打印列表中的元素对。我需要创建一个字典(首先是空的),我可以存储值,循环遍历列表以确保没有重复。
当我在列表中循环时,我需要获得一个随机数,我可以用它来删除一个元素。 使用pop方法从列表中删除随机选择的元素,将元素存储到变量,比如element1。重复它以创建element2。
将element1作为键插入,将element1映射到element2 对词典,并将其值设置为element2,即,如果我们调用 对[element1]以后它应该给我们element2的值。
使用字典的项目()和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 = {}
如何改进/添加此代码?
答案 0 :(得分:7)
使用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 :(得分:1)
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)
答案 2 :(得分:0)
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