简体   繁体   English

用两个列表中的随机元素创建字典列表-python

[英]create a list of dictionaries with randomised elements from two lists - python

Is there a way in python to perform randomization between two lists within a list and have a dictionary returned? python中是否有办法在列表中的两个列表之间执行随机化并返回字典?

For example, from: 例如,来自:

[[1,2,3,4], ['a','b','c','d']]

to: 至:

[{3:'a'}, {1:'d'}, {2:'c'}, {4:'b'}]

What's the best way to achieve this? 实现此目标的最佳方法是什么? Using a list comprehension? 使用列表理解? My two lists are actually very large, so I'm wondering whether there's a more efficient alternative. 我的两个列表实际上很大,所以我想知道是否有更有效的选择。

import random
keys, values = [[1,2,3,4], ['a','b','c','d']]
random.shuffle(values)
result =  [{k:v} for k, v in zip(keys, values)]

produces a list such as: 产生一个列表,例如:

In [7]: result
Out[7]: [{1: 'd'}, {2: 'b'}, {3: 'c'}, {4: 'a'}]

A more memory-efficient alternative would be to use an iterator: 内存效率更高的替代方法是使用迭代器:

import itertools as IT
result = ({k:v} for k, v in IT.izip(keys, values))

The larger question is why you would want a sequence of tiny dicts. 更大的问题是为什么您想要一系列小命令。 Wouldn't it be more useful to have one dict, such as the one produced by Steven Rumbalski's answer? 像史蒂文·鲁姆巴尔斯基的回答所产生的那样,做出一则命令会更有用吗?

Or, if you really do just want a randomized pairing, perhaps an iterator of tuples would suffice: 或者,如果您确实只想要随机配对,则元组的迭代器可能就足够了:

result = IT.izip(keys, values)

This creates a single dictionary rather than a list of single item dictionaries as your question requests. 这将创建一个字典,而不是您的问题要求的单个项目词典的列表。 If you really want that, use unutbu's answer . 如果您确实需要,请使用unutbu的答案

import random

a = [1,2,3,4]
b = ['a','b','c','d']

random.shuffle(a)
result = dict(zip(a, b))

If you cannot mutate your source lists: 如果您无法变更来源清单:

dx = range(len(a))
random.shuffle(dx)
dict(zip((a[i] for i in dx), b))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM