一个问题源于(1) 和(20) 不是元组(正如cmets 中的Ilja Everilä 所指出的那样)。由于它们实际上是int 类型,因此您不能迭代它们或使用[] 来索引。
首先是关于enumerate() 的注释,您使用不正确。这个函数返回一个 (index, value) 的元组。更多信息here。
如果无法更改源数据,您可以稍微修改代码以获得所需的结果。像以前一样循环元组,但使用isinstance 检查元素是否为int。
graph = {}
for i, x in enumerate(o):
graph[x] = {}
if isinstance(n[i], int):
graph[x][n[i]] = c[i]
else:
for j in range(len(n[i])):
graph[x][n[i][j]] = c[i][j]
print graph
#{0: {1: 30, 2: 70}, 1: {1: 20}}
这段代码的else块可以进一步简化,使用zip():
graph = {}
for i, x in enumerate(o):
graph[x] = {}
if isinstance(n[i], int):
graph[x][n[i]] = c[i]
else:
for y, z in zip(n[i], c[i]):
graph[x][y] = z
print graph
#{0: {1: 30, 2: 70}, 1: {1: 20}}
但是,更好的解决方案是将源数据 n 和 c 更改为仅包含元组:
def make_tuple(x):
return x if isinstance(x, tuple) else (x, )
new_n = map(make_tuple, n)
new_c = map(make_tuple, c)
那么上面的代码就不需要isinstance()检查了,可以简化为:
graph = {}
for i, x in enumerate(o):
graph[x] = {}
for y, z in zip(new_n[i], new_c[i]):
graph[x][y] = z
print graph
#{0: {1: 30, 2: 70}, 1: {1: 20}}
我们可以进一步简化为:
graph = {}
for ko, N, C in zip(o, new_n, new_c):
graph[ko] = {}
for kn, vc in zip(N, C):
graph[ko][kn] = vc
print graph
#{0: {1: 30, 2: 70}, 1: {1: 20}}
或者如果到紧凑的一个班轮(直接将上面的代码块翻译成字典理解):
graph = {ko: {kn:vc for kn, vc in zip(N, C)} for ko, N, C in zip(o, new_n, new_c)}
print graph
#{0: {1: 30, 2: 70}, 1: {1: 20}}