如何在Python中的另一个列表中的列表中获取单个数字?

时间:2015-11-15 21:58:29

标签: python python-2.7

我完全不知道如何弄清楚如何在列表中获取个别数字

这是我的代码:

infinity = 1000000 
invalid_node = -1  

class Node:
    previous = invalid_node
    distFromSource = infinity
    visited = False

def populateNetwork(fileName):

    network = []
    networkFile = open(fileName, "r")
    for line in networkFile:
        network.append(map(int, line.strip().split(',')))
    return network

def populateNodeTable(network, StartNode):
    nodeTable = []
    for node in network:
        nodeTable.append(Node())
    nodeTable[StartNode].distFromSource = 0
    nodeTable[StartNode].visited = True
    return nodeTable

network = populateNetwork('network.txt')
nodeTable = populateNodeTable(network, 1)
nodeTable2 = populateNodeTable(network, 2)
print "Visited Nodes"
for node in nodeTable:
    print node.previous, node.distFromSource, node.visited
print
print "This is what is inside network"
for line in network:
    print line

print
print "what is inside index 6"
print network[6]

这是输出:

Visited Nodes
-1 1000000 False
-1 0 True
-1 1000000 False
-1 1000000 False
-1 1000000 False
-1 1000000 False
-1 1000000 False

This is what is inside network
[0, 2, 4, 1, 6, 0, 0]
[2, 0, 0, 0, 5, 0, 0]
[4, 0, 0, 0, 0, 5, 0]
[1, 0, 0, 0, 1, 1, 0]
[6, 5, 0, 1, 0, 5, 5]
[0, 0, 5, 1, 5, 0, 0]
[0, 0, 0, 0, 5, 0, 0]

what is inside index 6
[0, 0, 0, 0, 5, 0, 0]

我的问题是,如何获取用于计算的索引中的单个数字?所以例如index [1]包含“0,2,4,1,6,0,0”,我将使用这些数字进行加法,所以0 + 2 + 4 + 1 + 6 + 0 + 0 = 13我真的很困惑。

1 个答案:

答案 0 :(得分:1)

print network[0] # 0, 2, 4, 1, 6, 0, 0

print network[0][0] # 0
print network[0][1] # 2
print network[0][2] # 4

for x in network[0]:
   print x
# 0
# 2
# 4
# 1
# 6
# 0
# 0

print sum(network[0]) # 13