首页 > 解决方案 > 从由多个列表组成的字典中,从每个列表中选择一个元素

问题描述

可以说我有一个这样的列表字典:

lists= {'pet': ["dog", "cat", "parrot"],
        'amount': [1,2,3],
        'food': ["canned", "dry"]}

我想从每个列表中随机选择一个元素,所以结果是这样的:

{'amount': 2, 'food': 'canned', 'pet': 'cat'}

使用 Python 实现它的最简单方法是哪种?

标签: pythonpython-3.xlistdictionaryrandom

解决方案


你试过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'}

我个人喜欢前两个选项。


推荐阅读