6 python random dictionary python-2.7
我有一本字典:
>>> print(dict)
{'gs': ['bags', 'begs', 'bogs'],
'le': ['Cole', 'Dale', 'Dole'],
'll': ['Ball', 'Bell', 'Bill']}
Run Code Online (Sandbox Code Playgroud)
对于每一个键,我只想从列表中选择一个单词(随机).输出如下:
{'gs': begs, 'le': 'Cole', 'll': 'Bill'}
Run Code Online (Sandbox Code Playgroud)
等等.
我已经尝试了大量的东西,但没有人给我一个字,用于字典的每个键.有一个简单的方法吗?
只需使用random.choice
字典的值,只用一个名称作为值重建字典理解
import random
d = {'gs': ['bags', 'begs', 'bogs'],
'le': ['Cole', 'Dale', 'Dole'],
'll': ['Ball', 'Bell', 'Bill']}
result = {k:random.choice(v) for k,v in d.items()}
Run Code Online (Sandbox Code Playgroud)
一个输出:
{'gs': 'bogs', 'le': 'Dale', 'll': 'Bell'}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
68 次 |
最近记录: |