在python中从文件生成特殊列表

时间:2014-04-07 10:22:10

标签: python file parsing

我有一个这样的文件:

one:two:three
four:five:six
seven:height:nine

依旧...... 我想要的是正确解析它以获得这种变量:

myVar = [("one", "two", "three"), ("four", "five", "six"), ("seven", "height", "nine")]

当然,文件不会在九点停止,之后会有很多行。

我怎样才能在Python中这样做?

谢谢!

3 个答案:

答案 0 :(得分:2)

with open('your file') as f:
    myVar = [ tuple(a.split(':')) for a in f.read().split() ]

print myVar

输出

[('one', 'two', 'three'), ('four', 'five', 'six'), ('seven', 'height', 'nine')]

答案 1 :(得分:2)

使用列表理解:

with open('filename') as f:
    myVar = [line.rstrip().split(':') for line in f]

如果您需要列表到元组,请将line.rstrip().split(':')传递给tuple()

tuple(line.rstrip().split(':'))

答案 2 :(得分:2)

您正在处理的数据看起来像分隔符。我建议使用csv.reader,就像这样

import csv
with open("Input.txt") as in_file:
    reader = csv.reader(in_file, delimiter=':')
    print [row for row in reader]

您可以将其转换为元组,就像这样

    print [tuple(row) for row in reader]