在文件列表中创建列表

时间:2014-11-30 14:50:43

标签: python list python-3.x

我正在尝试通过读取文件在列表中创建Python列表。该文件包含以下行:

12, 'MWSTRES1', 'K1317055', 1
15, 'MWSTRES1', 'K1416241', 3
13, 'MWSTRES1', 'K1316235', 8
9, 'BTBITSPQ', 'J03016235', 3
1, 'PLAUSP01', 'K1316235', 2
2, 'VTNTBMOT', 'K1316237', 9
4, 'VTNTBMOT', 'K1316239', 13

代码

combs = []
with open('file3', 'r') as f:
    result = [line.split(',')[:4] for line in f]
print(result)
print(sorted(result, key=lambda t: (t[0], t[1])))

代码生成的生成列表不正确,如图所示

[['12', " 'MWSTRES1'", " 'K1317055'", ' 1\n'], ['15', " 'MWSTRES1'", " 'K1416241'", ' 3\n'], ['13', " 'MWSTRES1'", " 'K1316235'", ' 8\n'], ['9', " 'BTBITSPQ'", " 'J03016235'", ' 3\n'], ['1', " 'PLAUS
P01'", " 'K1316235'", ' 2\n'], ['2', " 'VTNTBMOT'", " 'K1316237'", ' 9\n'], ['4', " 'VTNTBMOT'", " 'K1316239'", ' 13']]

我希望创建的列表看起来像这样

[[12, 'MWSTRES1', 'K1317055', 1], [15, 'MWSTRES1', 'K1416241', 3], [13, 'MWSTRES1', 'K1316235', 8], [9, 'BTBITSPQ', 'J03016235', 3], [1, 'PLAUSP01', 'K1316235', 2], [2, 'VTNTBMOT', 'K1316237', 9], [4, 'VTNTBMOT', 'K1316239', 13]]

错误的列表阻止我获得正确的排序输出

[['1', " 'PLAUSP01'", " 'K1316235'", ' 2\n'], ['12', " 'MWSTRES1'", " 'K1317055'", ' 1\n'], ['13', " 'MWSTRES1'", " 'K1316235'", ' 8\n'], ['15', " 'MWSTRES1'", " 'K1416241'", ' 3\n'], ['2', " 'VTNTBMOT'", " 'K1316237'", ' 9\n'], ['4', " 'VTNTBMOT'", " 'K1316239'", ' 13'], ['9', " 'BTBITSPQ'", " 'J03016235'", ' 3\n']]

有人可以告诉我如何创建正确的列表吗?

1 个答案:

答案 0 :(得分:3)

要获得所需的结果,您需要做一些事情。

def clean_line(line):
    # for the sake of completeness, remove surrounding blanks from all columns
    parts = [part.strip() for part in line.strip().split(',')[:4]]

    # first turn first and last columns to integers
    parts[0] = int(parts[0])
    parts[-1] = int(parts[-1])

    # single quotes need to be removed from the columns in the middle
    parts[1:-1] = [part.strip("'") for part in parts[1:-1]]
    return parts

最后,您的代码应该看起来像这样:

combs = []
with open('file3', 'r') as f:
    result = [clean_line(line) for line in f]
print(result)
print(sorted(result, key=lambda t: (t[0], t[1])))

使用此文件,从文件创建的列表如下所示(为了便于阅读,格式已更改):

[
    [12, 'MWSTRES1', 'K1317055', 1],
    [15, 'MWSTRES1', 'K1416241', 3],
    [13, 'MWSTRES1', 'K1316235', 8],
    [9, 'BTBITSPQ', 'J03016235', 3],
    [1, 'PLAUSP01', 'K1316235', 2],
    [2, 'VTNTBMOT', 'K1316237', 9],
    [4, 'VTNTBMOT', 'K1316239', 13]
]