Skip to content

Instantly share code, notes, and snippets.

@luw2007
Created June 21, 2013 02:04
Show Gist options
  • Select an option

  • Save luw2007/5828358 to your computer and use it in GitHub Desktop.

Select an option

Save luw2007/5828358 to your computer and use it in GitHub Desktop.
acmerfight 通过“googlegroups.com” 发送至 python-cn 有一个文件 下面为文件中的前5行数据,注意每行数据存储的元素数量不固定 [1, 2, 3, 4] [1, 2, 3, 5] [1, 9, 4] [10, 11, 12, 7] [10, 12, 4, 5] 我要明确知道上一级到下一级的完整从属关系。 要求输出结果为 {1:{2:{3:[4, 5]}, 9:[4]}} {10:{11:{12:[7]}, 12:{4:[5]}}}
s = [[1, 2, 3, 4],
[1, 2, 3, 5],
[1, 9, 4],
[10, 11, 12, 7],
[10, 12, 4, 5]]
c = {1:{2:{3:[4, 5]}, 9:[4]}, 10:{11:{12:[7]}, 12:{4:[5]}}}
r = {}
for row in s:
_r = r
if len(row) < 2:
print 'error line', row
for i in row[:-2]:
_r = _r.setdefault(i,{})
k, v = row[-2:]
_r.setdefault(k,[]).append(v)
assert c == r
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment