假设我有一份人员名单

['foo','bar','baz']

和一份物品 list

['hat','bag','ball','bat','shoe','stick','pie','phone']

我想给每个人分配等量的物品,就像这样

{
'foo':['hat','bat','stick'],
'bar':['bag','shoe','phone'],
'baz':['ball','pie']
}

我认为itertools是这个工作,但我似乎找不到正确的函数,因为大多数itertools函数似乎只在一个对象上工作.

编辑:订单确实有not个问题.我只是想随机地给每个人分配等量的物品.

推荐答案

另一个解决方案,使用itertools.cycle:

import random
from itertools import cycle

persons = ["foo", "bar", "baz"]
items = ["hat", "bag", "ball", "bat", "shoe", "stick", "pie", "phone"]

random.shuffle(items)

out = {}
for p, i in zip(cycle(persons), items):
    out.setdefault(p, []).append(i)

print(out)

打印(例如):

{
    "foo": ["phone", "pie", "bat"],
    "bar": ["bag", "stick", "hat"],
    "baz": ["shoe", "ball"],
}

如果条目可能比人少,并且每个人都应该在输出词典中有关键字,则可以使用:

import random
from itertools import cycle

persons = ["foo", "bar", "baz"]
items = ["hat", "bag", "ball", "bat", "shoe", "stick", "pie", "phone"]

random.shuffle(items)
random.shuffle(persons)  # to randomize who gets fewest items

out = {p: [] for p in persons}
for lst, i in zip(cycle(out.values()), items):
    lst.append(i)

print(out)

Python相关问答推荐

我从带有langchain的mongoDB中的vector serch获得一个空数组

难以在Manim中正确定位对象

'discord.ext. commanders.cog没有属性监听器'

运行终端命令时出现问题:pip start anonymous"

Pandas - groupby字符串字段并按时间范围 Select

在Wayland上使用setCellWidget时,try 编辑QTable Widget中的单元格时,PyQt 6崩溃

迭代嵌套字典的值

创建可序列化数据模型的最佳方法

使用groupby方法移除公共子字符串

在Python中计算连续天数

手动设置seborn/matplotlib散点图连续变量图例中显示的值

搜索按钮不工作,Python tkinter

在Docker容器(Alpine)上运行的Python应用程序中读取. accdb数据库

比Pandas 更好的 Select

Python日志(log)模块如何在将消息发送到父日志(log)记录器之前向消息添加类实例变量

从源代码显示不同的输出(机器学习)(Python)

如何训练每一个pandaprame行的线性回归并生成斜率

极点替换值大于组内另一个极点数据帧的最大值

Pythonquests.get(Url)返回Colab中的空内容

Pandas ,快速从词典栏中提取信息到新栏