python - 为列表中的每个项目随机分配一对而不重复
问题描述
所以我有一个列表,我想将这些值“分配”给不同的随机值。
例如。
list = ["dog", "cat", "rat", "bird", "monkey"]
我想要一个像这样的输出
{"dog": "bird", "cat": "monkey", "rat": "dog", "bird": "rat", "monkey": "cat"}
我想要的是:
- 不能将值分配给自身,例如不是 {"cat": "cat"}
- 一个值只能分配一次,例如不能分配 {"cat": "dog", "rat": "dog"}
- 值不能相互分配,例如 not {"cat": "dog", "dog", "cat"}
我试过这段代码:
def shuffle_recur(_list):
final = {}
not_done = copy.deepcopy(_list)
for value in _list:
without_list = not_done.copy()
if value in without_list :
without_list.remove(value)
if value in final.values():
for final_key, final_value in final.items():
if final_value == value:
print(final_value, ' ', final_key)
if final_key in without_list :
without_list.remove(final_key)
if len(without_list) < 1:
print('less')
return shuffle_recur(_list)
target = random.choice(without_list)
not_done.remove(target)
final[value] = target
print('{} >> {}'.format(value, target))
return final
但它非常混乱,我认为这不是最好的方法。有什么更好的方法来做到这一点?
解决方案
您可以只构建一个随机排序的项目列表,然后将它们配对为键值
一方面,您将获取列表,另一方面从 item 旋转相同的列表values[1:] + [values[0]]
,然后将两者压缩成 2×2 对,并从这些对中构建一个 dict
values = ["dog", "cat", "rat", "bird", "monkey"]
shuffle(values)
result = dict(zip(values, values[1:] + [values[0]]))
例子
洗牌给
['bird', 'dog', 'rat', 'monkey', 'cat']
旋转给
['dog', 'rat', 'monkey', 'cat', 'bird']
拉链给
[('bird', 'dog'), ('dog', 'rat'), ('rat', 'monkey'), ('monkey', 'cat'), ('cat', 'bird')]
然后每一对变成一个映射
print(values) # ['bird', 'dog', 'rat', 'monkey', 'cat']
print(result) # {'bird': 'dog', 'dog': 'rat', 'rat': 'monkey', 'monkey': 'cat', 'cat': 'bird'}
如果您不映射彼此,只需shuffle
第二次
mappings = list(zip(values, values[1:] + [values[0]]))
shuffle(mappings)
result = dict(mappings)
推荐阅读
- javascript - 为什么 php 处理程序不发送电子邮件(在 Nginx 服务器上运行的站点)
- mobile - 有人可以帮助我使用移动应用程序的 XPages DataView 控件吗?
- excel - 尝试根据第一列删除重复项
- r - RMarkdown - 第二个内联代码显示代码块而不是值
- javascript - \PlaylistItems:list API 在删除视频时返回少于 totalResults
- google-cloud-firestore - 在 Flutter 应用程序中包含 Firestore 的问题
- django - Django ORM 验证数据库中的一行
- hive - Kafka 到 Flink 到 Hive - 写入失败
- ansible - 在 Ansible Jinja2 模板的默认过滤器中使用变量
- ios - 在 UIButton 的边缘动态对齐图像