我从txt文件中读取了一个矩阵,但我无法在其上调用特定元素
矩阵:
['5x5\n',
'0.49832186379667975\t0.08107739538827341\t0.34862619622310764\t0.6371236836985522\t0.38901192241601756\t\n'...
代码:
f = open('matrix.txt','r+')
lines=f.readlines()
print(lines[1][2])
>>>4
但它应该是0.34862619622310764 我该如何编入索引?
答案 0 :(得分:0)
您正在索引字符串,而不是列表。您看到的是readValue(objectNode)
,而不是'4'
。 (为清楚起见,请勿使用4
或使用print(x)
。)
你忘记了每行print(repr(x))
。
这样做的典型方法是:
.split('\t')
如果您想将字符串转换为实际数字,请不要忘记在整个过程中解析它们:
with open('matrix.txt') as f:
lines = [line.split('\t') for line in f]
# Here the file auto-closes
number_lines = [[float(s) for s in line.split('\t') if s] for line in f]
部分是必需的,因为您的行包含尾随if s
,因此吐出后的列表将包含无法转换为数字的'\t'
。空字符串是假的,因此它将被过滤掉。
但是第一行会失败;所以你必须以不同的方式处理它:
''
答案 1 :(得分:0)
就这样:
def ucs(G, v):
visited = set() # set of visited nodes
q = queue.PriorityQueue() # we store vertices in the (priority) queue as tuples
# (f, n, path), with
# f: the cumulative cost,
# n: the current node,
# path: the path that led to the expansion of the current node
q.put((0, v, [v])) # add the starting node, this has zero *cumulative* cost
# and it's path contains only itself.
while not q.empty(): # while the queue is nonempty
f, current_node, path = q.get()
visited.add(current_node) # mark node visited on expansion,
# only now we know we are on the cheapest path to
# the current node.
if current_node.is_goal: # if the current node is a goal
return path # return its path
else:
for edge in in current_node.out_edges:
child = edge.to()
if child not in visited:
q.put((current_node_priority + edge.weight, child, path + [child]))