【问题标题】:Data structure in PythonPython中的数据结构
【发布时间】: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


【解决方案1】:

您可以将list_price 变成一个迭代器,然后使用next 获取一个接一个的值:

>>> 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'}]

当然,您不必使用列表推导式,但也可以使用嵌套循环做同样的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-23
    • 1970-01-01
    • 2018-01-22
    • 2016-09-15
    • 2017-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多