【发布时间】:2014-06-14 11:43:10
【问题描述】:
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
我想将我的数据结构创建为:
[
{'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()
【问题讨论】:
-
你有什么疑问?这显然是可能的。
-
我们是否应该假设每个名称只从
list_price中获取下一个len(size)元素?这样做很简单,但从起始结构来看,这并不是我们想要的。 -
你有没有尝试过,下面你有一个很好的答案,你会更新你的问题..
-
我认为在这里使用 defaultdict 没有多大意义。我猜你可以使用 defaultdict 在 size_price 子字典中生成下一个条目,但这只有在你以正确的顺序访问这些值时才有效。
-
我刚刚添加了正确的格式!
标签: list python-2.7 dictionary data-structures