Python中的数据结构 [英] Data structure in Python

查看:109
本文介绍了Python中的数据结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

names=['Peter', 'John']
size = ['X', 'M', 'L']
list_price =  [1, 2, 3, 4, 5, 6]  # There are 2 people will buy 3 size of shirt

我想创建我的数据结构:

I want to create my data structure into:

[
{'name': u'Peter', 'size_price': defaultdict(<type 'int'>, { 'X': 1, 'M':2, 'L': 3})}, 
{'name': 'John', 'size_price': defaultdict(<type 'int'>, {'X':4, 'M':5, 'L':6})}
] 

我更喜欢做defaultdict()

I prefer to do defaultdict()

推荐答案

您可以将 list_price 转换为迭代器,然后使用 next 在另一个值之后获取一个值:

You can turn list_price into an iterator and then use next to get one value after the other:

>>> iterator = iter(list_price)
>>> [{"name": n, "size_price": {s: next(iterator) for s in size}} for n in names]
[{'size_price': {'X': 1, 'M': 2, 'L': 3}, 'name': 'Peter'}, 
 {'size_price': {'X': 4, 'M': 5, 'L': 6}, 'name': 'John'}]

当然你不必使用列表的理解,但可以做嵌套循环也是一样的。

Of course you do not have to use a list comprehension but can do the same thing with nested loops as well.

这篇关于Python中的数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆