从由多个列表组成的字典中,从每个列表中选择一个元素

假设我有一个这样的列表字典:

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'}

不过我个人喜欢前两个选项。

  • ~~for the first example, `{k: choice(v) for k, v in lists.items()}` might be a little cleaner.~~ quick on the edit! nice.
  • @acushner Yes that's fine thank you. I think my previous solution would only be preferable if lists were large and we didn't want to generate an additional view using .items() but this is cleaner, yes.

以上是从由多个列表组成的字典中,从每个列表中选择一个元素的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>