可以说我有一个这样的列表字典:
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'}
我个人很喜欢前两个选项。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句