python - 从由多个列表组成的字典中,从每个列表中选择一个元素
问题描述
可以说我有一个这样的列表字典:
lists= {'pet': ["dog", "cat", "parrot"],
'amount': [1,2,3],
'food': ["canned", "dry"]}
我想从每个列表中随机选择一个元素,所以结果是这样的:
{'amount': 2, 'food': 'canned', 'pet': 'cat'}
使用 Python 实现它的最简单方法是哪种?
解决方案
你试过random.choice
吗?
from random import choice
{k: choice(v) for k in lists.items()} # use lists.iteritems() in python 2.x
# {'pet': 'parrot', 'amount': 3, 'food': 'canned'}
或者,如果您想lists
就地更新,请使用
for k, v in lists.items():
lists[k] = choice(v)
lists
# {'pet': 'parrot', 'amount': 3, 'food': 'canned'}
或者,如果您的 python 版本支持有序的内置字典(>= cpython3.6,>= python3.7),您可以尝试将map
其用作功能替代:
dict(zip(lists, map(choice, lists.values())))
# {'pet': 'parrot', 'amount': 2, 'food': 'dry'}
我个人喜欢前两个选项。
推荐阅读
- javascript - 使用带有 react-chartjs-2 的 chartjs-chart-geo 插件实现等值线图
- ruby-on-rails - rails 6 ajax“remote:true”什么都不做
- javascript - 嵌入后获取用户输入(Discord.js)
- mysql - 使用 express 和 nodejs 插入 mysql
- sql - 使用空行和列将 Excel 工作簿导入 SQL 数据库
- java - 如何从数组列表中删除重复项
- python - 在这段代码中,有一个初始化问题导致我们的函数行为不正确。你能找到问题并解决它吗?
- c# - C#匿名类型`ToString`复杂?
- html - 如何将引号保留在引号内?
- algorithm - 页面大小更改的默认页码