![](/img/trans.png)
[英]How create dictionaries inside dictionaries, inside dictionaries… 'n' times
[英]How to create a list of n dictionaries
我正在学习Python,为了实践目的,我正在编写一个脚本来读取文件(包含一个简单图形格式的图形 ),并在图形上运行几个图形算法。
我想过将图形存储在n个字典的列表中,其中n是顶点的数量,顶点的所有边都存储在字典中。
我试过这个
edges = [{} for i in xrange(num_vertexes)]
for line in file:
args = line.split(' ')
vertex1 = int(args[0])
vertex2 = int(args[1])
label = int(args[2])
edges[vertex1][vertex2] = label
但我在最后一行收到此错误:
IndexError:列表索引超出范围
看起来vertex1
可能大于num_vertexes
。 假设从0开始的python索引和格式的wiki上的示例从1开始,最后一行的顶点数可能比索引的长度高1(我当然需要查看文件才能确定) )。 所以在python情况下, lst[0]
是第一个元素,而lst[n-1]
是最后一个元素,其中顶点1
是第一个元素, n
是最后一个元素。
所以这里的修复是使用vertex1 = int(args[0])-1
问题出在您的数据的某处,添加一些验证以确保您的代码不会阻塞不良数据。 如果一行有非数字,少于三个数字,或者如果vertex1 >= len(edges)
,则代码将失败。
edges = [{} for i in xrange(num_vertexs)]
for line in file:
args = line.split(' ')
if len(args) >= 3:
try:
vertex1 = int(args[0])
vertex2 = int(args[1])
label = int(args[2])
if vertex1 < len(edges):
edges[vertex1][vertex2] = label
else:
# value for vertex1 is too large
pass
except ValueError:
# you got some non-number data
pass
else:
# you got a line with not enough data
pass
如果需要,可以使用日志记录替换任何这些pass
语句(如果不打算使用它们,也可以删除else
两个else
块)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.