如何使列表成为字符串,然后是数组

时间:2018-02-14 00:56:40

标签: python spyder

import csv
with open('data1.txt', 'r') as f:
     fread = csv.reader(f, delimiter='\t')
     output = []
     for line in fread:
         output.append(line)
data_values = str(output[1:17]) #skip the first line and grab relevant data from lines 1 to 16
print(data_values)
usable_data_values = float(data_values)

现在,我正在尝试将包含两列数据的.txt文件转换为包含两列数据的数组。在这一点上,我已经提取了数据并拥有:

[['0.0000', '1.06E+05'], ['0.0831', '93240'], ['0.1465', '1.67E+05'],
['0.2587', '1.54E+05'], ['0.4828', '1.19E+05'], ['0.7448', '1.17E+05'],
['0.9817', '1.10E+05'], ['1.2563', '1.11E+05'], ['1.4926', '74388'], ['1.7299', '83291'], 
['1.9915', '66435'], ['3.0011', '35407'], ['4.0109', '21125'], ['5.0090', '20450'], 
['5.9943', '15798'], ['7.0028', '4785.2']]

我试图将这些数据变成可用的东西(我想我需要摆脱逗号,但我不熟悉Python,甚至不知道如何做到这一点)。将这些数字转换为可用的操作形式(乘法,加法,除法等)可以获得任何帮助!

1 个答案:

答案 0 :(得分:0)

我相信这是你能做的最好的事情。逗号很好,它们只是表示python list的单独元素。请注意,引号会消失,表示您不再处理文本字符串。

lst = [['0.0000', '1.06E+05'], ['0.0831', '93240'], ['0.1465', '1.67E+05'],
       ['0.2587', '1.54E+05'], ['0.4828', '1.19E+05'], ['0.7448', '1.17E+05'],
       ['0.9817', '1.10E+05'], ['1.2563', '1.11E+05'], ['1.4926', '74388'], ['1.7299', '83291'], 
       ['1.9915', '66435'], ['3.0011', '35407'], ['4.0109', '21125'], ['5.0090', '20450'], 
       ['5.9943', '15798'], ['7.0028', '4785.2']]

[list(map(float, i)) for i in lst]

# [[0.0, 106000.0],
#  [0.0831, 93240.0],
#  [0.1465, 167000.0],
#  [0.2587, 154000.0],
#  [0.4828, 119000.0],
#  [0.7448, 117000.0],
#  [0.9817, 110000.0],
#  [1.2563, 111000.0],
#  [1.4926, 74388.0],
#  [1.7299, 83291.0],
#  [1.9915, 66435.0],
#  [3.0011, 35407.0],
#  [4.0109, 21125.0],
#  [5.009, 20450.0],
#  [5.9943, 15798.0],
#  [7.0028, 4785.2]]