【问题标题】:mapping multiple lists to dictionary将多个列表映射到字典
【发布时间】:2012-09-17 09:47:14
【问题描述】:

我有 5 个列表,我想将它们映射到分层字典。

假设我有:

temp = [25, 25, 25, 25]
volt = [3.8,3.8,3.8,3.8]
chan = [1,1,6,6]
rate = [12,14,12,14]
power = [13.2,15.3,13.8,15.1]

我想要的字典是这样的:

{25:{3.8:{1:{12:13.2,14:15.3},6:{12:13.8,14:15.1}}}}

基本上字典结构是:

{temp:{volt:{chan:{rate:power}}}}

我尝试使用 zip 函数,但在这种情况下它没有帮助,因为顶层列表中的重复值

【问题讨论】:

  • 如何处理重复值?
  • 我只是想在示例中保持列表较小,但我的数据将包括例如:temp = [25,25,....,25,60,60,..... ,60,75,75,...] 我有这些重复值的唯一原因是因为功率值对应于该温度值...一旦列表映射到字典,我就没有用处了。
  • 由索引决定。例如 index = 2, temp = 25, volt = 3.8, chan = 1, rate = 14, power = 15.3

标签: python list dictionary mapping


【解决方案1】:

这只是稍微经过测试,但似乎可以解决问题。基本上,f 所做的就是创建一个 defaultdict 的 defaultdicts。

f = lambda: collections.defaultdict(f)
d = f()
for i in range(len(temp)):
    d[temp[i]][volt[i]][chan[i]][rate[i]] = power[i]

例子:

>>> print d[25][3.8][6][14]
15.1

(这个想法是从this answer to a related question借来的。)

【讨论】:

  • 我喜欢称这些为infinitedict = lambda: collections.defaultdict(infinitedict)
  • @jterrace 是的,实际上是您的一个回答启发了我。希望你不要介意。
【解决方案2】:

您可以尝试以下...我相信它可以满足您的需求

>>> # Given your sample data.
>>> ans = {}
>>> for (t, v, c, r, p) in zip(temp, volt, chan, rate, power):
...     if not t in ans:
...             ans[t] = {}
...     if not v in ans[t]:
...             ans[t][v] = {}
...     if not c in ans[t][v]:
...             ans[t][v][c] = {}
...     if not r in ans[t][v][c]:
...             ans[t][v][c][r] = p
>>> print ans
{25: {3.8: {1: {12: 13.2, 14: 15.3}, 6: {12: 13.8, 14: 15.1}}}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-31
    • 2010-09-19
    • 1970-01-01
    • 2018-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多