如何从一个文件分成多个列表解析线 [英] How to parse a line from a file into multiple lists

查看:165
本文介绍了如何从一个文件分成多个列表解析线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的文件。

I have a file that looks like this.

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

....等等

.... and so on

我要分析它才能使用BFS算法。我想:

I want to parse it in order to use BFS algorithm. I tried:

with open( "data.txt", "r" ) as input_data:
  input_list= [map(int,num.split()) for num in input_data.readlines()]

我想有一个像这样的字典,以申请BFS:

I want to have a dictionary like this in order to apply BFS:

data = { '1':['2'], '2':['1','5'] .....}

任何想法如何解析呢?

Any ideas how to parse it?

推荐答案

您输出包含字符串,这样你就可以跳过 INT 的电话。

Your output contains strings, so you can skip the int calls.

如果第一个元素是是关键,其余的值(忽略房间的名称),一个字典COM prehension是不够的:

If the first element is to be the key, the rest the values (ignoring the room name), a dict comprehension is enough:

with open( "data.txt", "r" ) as input_data:
    data = {elems[0]: elems[1:-1] 
            for line in input_data for elems in (line.split(','),)}

在elems(line.split(''),),单元将只有一个值( line.split的输出( ',') elems ;它能解决在COM prehension语法限制

The for elems in (line.split(','),) section assigns just one value (the output of line.split(',') to elems; it works around limitations in comprehension syntax.

由于这是逗号分隔的数据,我会使用 CSV 模块这里:

Since this is comma-separated data, I'd use the csv module here:

import csv

with open( "data.txt", "rb" ) as input_data:
    reader = csv.reader(input_data)
    data = {row[0]: row[1:-1] for row in reader}

正如你所看到的,这简化了处理每行显著。

As you can see, this simplifies handling each line significantly.

添加 INT()电话如果需要的:

data = {int(row[0]): map(int, row[1:-1]) for row in reader}

这篇关于如何从一个文件分成多个列表解析线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆