我正在尝试创建一个程序,将打印列表中的元素对.我需要创建一个字典(首先是空的),我可以在其中存储值,循环遍历列表以建立一对并确保没有重复.
当我在列表中循环时,我需要获得一个随机数,我可以用它来删除一个元素.使用pop方法从列表中删除随机选择的元素,将元素存储到变量,比如element1.重复它以创建element2.
通过将element1作为键插入到对词典中,并将其值设置为element2,即,如果我们稍后调用对[element1],它应该给我们element2的值,从而将element1映射到element2.
使用字典的items()和keys()方法打印结果.
问题是,我们唯一允许的函数是来自随机模块的random.randrange():(
例如:
list = ["Mother", "Father", "Aunt", "Uncle", "Brother", "Sister" ]
Run Code Online (Sandbox Code Playgroud)
程序的示例运行,这将创建3对,因为列表中有6个元素.
Pair 1: Mother and Aunt
Pair 2: Uncle and Sister
Pair 3: Brother and Father
Run Code Online (Sandbox Code Playgroud)
这是我现在的程序:
family = ["Mother", "Father", "Aunt", "Uncle", "Brother", "Sister" ]
for x in family:
pairs = {}
Run Code Online (Sandbox Code Playgroud)
如何改进/添加此代码?