当我运行以下代码时,我得到一个错误,说“列表索引必须是整数,而不是元组”。当我声明第一个和第二个变量时,会出现此错误。任何人都可以解释或修复此错误
globalViewDict = {'A': [('B', 6.5, 5001), ('F', 2.2, 5005), 'A', '2'],
'B': [('A', 6.5, 5000), ('C', 1.1, 5002), ('D', 4.2, 5003), ('E', 3.2, 5004), 'B', '4'],
'C': [('B', 1.1, 5001), ('D', 1.6, 5003), 'C', '2'],
'D': [('F', 0.7, 5005), ('B', 4.2, 5001), ('C', 1.6, 5002), ('E', 2.9, 5004), 'D', '4'],
'E': [('B', 3.2, 5001), ('D', 0.7, 5003), ('F', 6.2, 5005), 'E', '3'],
'F': [('A', 2.2, 5000), ('D', 0.7, 5003), ('E', 6.2, 5004),'F','3']}
def dijkstrawPhase():
global globalViewDict
pprint.pprint(globalViewDict)
#print "globalViewDict:", globalViewDict
print""
tempList =[]
temptup = ()
newList = []
x=0
for key,value in globalViewDict.iteritems():
x=0
i=0
neighborsOfPacket = int(value[-1])
while x < neighborsOfPacket:
j=0
id = str(value[i][0])
cost = float(value[i][1])
temptup =(key,id,cost)
i = i + 1
x = x + 1
tempList.append(temptup)
print "tempList\n",pprint.pprint(tempList)
for x in tempList:
first = tempList[x][0]
second = tempList[x][1]
j=0
for j in tempList:
if tempList[j][0]==second and tempList[j][i] == first:
print "nothng dne"
else:
newList.append(tempList[x])
print "newList\n",pprint.pprint(newList)
dijkstrawPhase()
答案 0 :(得分:3)
在顶部的for
循环中,您可以向tempList
添加一些元组。
temptup =(key,id,cost)
tempList.append(temptup)
在底部循环中,您可以:
for x in tempList:
first = tempList[x][0]
second = tempList[x][1]
x
指的是列表中的项目 - 元组,而不是索引。你想要的更像是这样:
for x in tempList:
first = x[0]
second = x[1]