2017-01-02 102 views
-2

当我运行下面的代码,我得到一个错误说当我第一次和第二次声明变量“列表索引必须是整数,而不是元组”。这个错误occours。谁能解释或修正此错误“列表索引必须是整数,而不是元组”

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() 

回答

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] 
相关问题