我在一个表示座位的字典中有固定的键,我想用从列表(人)中随机选择的值填充字典。
下面我尝试从列表people中随机选择一个元素,并将该元素作为值放入字典d到键A1,但失败了。然后将从列表people中随机选择的元素作为键A2的值。
如果我正在处理一个数据帧,我会在for循环结束时使用append。但是追加对字典不起作用。对如何继续有什么想法吗?
from random import randint
seats =['A1', 'A2', 'A3', 'A4']
people = ['A', 'B', 'C', 'D']
d = {k:None for k in seats}
while people:
s = [people.pop(randint(0, len(people) - 1)) for _ in range(1)]
for key in d:
d[key] = s
问题是你的循环for key in d
将弹出的人分配给每个关键,你可能不需要
这要简单得多,迭代并分配一个随机元素从列表中弹出
d = {}
for seat in seats:
d[seat] = people.pop(randint(0, len(people) - 1))
或者将键与打乱的人名列表配对
from random import shuffle
shuffle(people)
d = dict(zip(seats, people))
或甚至sample
,以避免修改people
列表或复制它
from random import sample
d = dict(zip(seats, sample(people, k=len(people))))
这就是推导式的作用:创建基于其他集合的新集合。
from random import shuffle
seats =['A1', 'A2', 'A3', 'A4']
people = ['A', 'B', 'C', 'D']
shuffle(people)
d = {k:v for (k,v) in zip(seats,people)}
print(d)
示例输出:
{'A1': 'B', 'A2': 'A', 'A3': 'D', 'A4': 'C'}
您希望seats
是dict
的键,people
的随机排序是相应的值。
import random
seats =['A1', 'A2', 'A3', 'A4']
people = ['A', 'B', 'C', 'D']
random.shuffle(people)
d = dict(zip(seats, people))