将给定文本更改为列表列表

时间:2015-08-07 04:39:57

标签: python python-3.x numpy

我在给定文件中有以下文字:

1234,A,7.99,10.3,12.8,101,0.11843,0.27276,0.30101  
87635,B,19.69,21.25,130,1203,0.1096,0.1599,0.1974

首先,我想摆脱前面的123487635,我还想将A更改为整数"1"和{{1进入整数B

这是我的代码:

"0"

这是我想要的输出:

def convert(file):
    data = open(file, 'r')
    list1 = []
    for line in data:
        line_data = line.strip().split(',')
        if line_data[0] == "B":
            line_data[0] = 0
        else:
            line_data[0] = 1
        for i in range(len(line)):
             datalist.append(line)
    list1 = np.array(list1), float
    data.close()
    return list1

我目前得到的输出是[[1234,A,7.99,10.3,12.8,101,0.11843,0.27276,0.30101], [87635,B,19.69,21.25,130,1203,0.1096,0.1599,0.1974]] 个字符串,而不是列表列表。

1 个答案:

答案 0 :(得分:3)

您收到list strings,因为您要将该列表附加为 -

datalist.append(line)

这会附加原始line,而不是已更改的line_data。此外,line_data中的所有元素仍然是字符串(期望第一个元素),因为您永远不会将它们转换为int。

这里最简单的方法是使用csv模块,将文件解析为csv,然后从返回的每一行中弹出第一个元素,然后更改第二个元素(现在删除之后的第一个元素,如你所愿)。示例 -

def convert(file):
    import csv
    lst = []
    with open('<filename>','r') as f:
        reader = csv.reader(f)
        for row in reader:
                row.pop(0)
                if row[0] == 'B':
                        row[0] = 0
                else:
                        row[0] = 1
                lst.append(list(map(float, row)))
    return lst

示例/演示 -

我的a.csv -

1234,A,7.99,10.3,12.8,101,0.11843,0.27276,0.30101  
87635,B,19.69,21.25,130,1203,0.1096,0.1599,0.1974

代码和结果 -

>>> import csv
>>> with open('a.csv','r') as f:
...     reader = csv.reader(f)
...     lst = []
...     for row in reader:
...             row.pop(0)
...             if row[0] == 'B':
...                     row[0] = 0
...             else:
...                     row[0] = 1
...             lst.append(list(map(float, row)))
...
'1234'
'87635'
>>> lst
[[1.0, 7.99, 10.3, 12.8, 101.0, 0.11843, 0.27276, 0.30101], [0.0, 19.69, 21.25, 130.0, 1203.0, 0.1096, 0.1599, 0.1974]]