我有一个像这样的文件。你知道吗
1,2,Room1 # first is the current room, the rest of the numbers the neighbours - maximum 4, and the last the name of the room
2,1,5,Room2
5,2,332,Room3
。。。。等等
我想解析它以便使用BFS算法。我试过:
with open( "data.txt", "r" ) as input_data:
input_list= [map(int,num.split()) for num in input_data.readlines()]
我想要一本这样的字典,以便应用BFS:
data = { '1':['2'], '2':['1','5'] .....}
你知道怎么解析吗?你知道吗
你在找这样的东西吗?你知道吗
可能会更优化
您的输出包含字符串,因此可以跳过
int
调用。你知道吗如果第一个元素是键,其余元素是值(忽略房间名称),那么一个dict理解就足够了:
for elems in (line.split(','),)
部分只为line.split(',')
的输出分配一个值;它绕过了理解语法的限制。你知道吗因为这是逗号分隔的数据,所以我在这里使用^{} module :
如您所见,这大大简化了对每一行的处理。你知道吗
如果需要,添加
int()
调用:相关问题 更多 >
编程相关推荐