我有以下列表
['0, 0, 0.16548735788092,\n',
'1, 3.90625E-05, 0.368149412097409,\n',
'2, 7.8125E-05, 0.184674297925085,\n',
'3, 0.0001171875, 0.00359755125828087,\n',
'4, 0.00015625, 0.0131910212803632,\n',
'5, 0.0001953125, 0.24703185306862,\n',
'6, 0.000234375, 0.474876766093075,\n',]
BWhich我是从
获得的data = f.readlines()
我想将此列表转换为包含3列的数组。感谢
答案 0 :(得分:2)
我们按行重复。然后,对于每一行,我们在,
上拆分并将相应的值分配给临时值,然后将一个包含三个条目的列添加到数组
array=[]
for line in f.readlines():
a_0,a_1,a_2,_=line.split(",")
array.append([a_0,a_1,a_2])
答案 1 :(得分:2)
[list(map(float, i.strip().split(',')[:-1])) for i in mylist]
输出:
[[0.0, 0.0, 0.16548735788092],
[1.0, 3.90625e-05, 0.368149412097409],
[2.0, 7.8125e-05, 0.184674297925085],
[3.0, 0.0001171875, 0.00359755125828087],
[4.0, 0.00015625, 0.0131910212803632],
[5.0, 0.0001953125, 0.24703185306862],
[6.0, 0.000234375, 0.474876766093075]]
答案 2 :(得分:2)
如果您希望将列表作为数字,请转到:
list_3d = []
for line in data:
columns = list(map(float, line.replace(' ','').split(',')[:-1]))
list_3d.append(columns)
print(list_3d)
答案 3 :(得分:2)
您可以尝试这样的事情:
data=['0, 0, 0.16548735788092,\n',
'1, 3.90625E-05, 0.368149412097409,\n',
'2, 7.8125E-05, 0.184674297925085,\n',
'3, 0.0001171875, 0.00359755125828087,\n',
'4, 0.00015625, 0.0131910212803632,\n',
'5, 0.0001953125, 0.24703185306862,\n',
'6, 0.000234375, 0.474876766093075,\n',]
print(list(map(lambda x:list(map(float,x.split(',')[:-1])),data)))
输出:
[[0.0, 0.0, 0.16548735788092], [1.0, 3.90625e-05, 0.368149412097409], [2.0, 7.8125e-05, 0.184674297925085], [3.0, 0.0001171875, 0.00359755125828087], [4.0, 0.00015625, 0.0131910212803632], [5.0, 0.0001953125, 0.24703185306862], [6.0, 0.000234375, 0.474876766093075]]
答案 4 :(得分:1)
您可以使用string.split,', '
作为分隔符。
new_list = []
for line in data:
line = line.strip() # get rid of \n
line = line.strip(',') # get rid of trailing comma
line = line.split(', ') # split into items
new_list.append(line) # add to the new list
然后输出:
[['0', '0', '0.16548735788092'],
['1', '3.90625E-05', '0.368149412097409'],
...
答案 5 :(得分:1)
这是一种方式。输入列表为lst
。输出是3个元组的列表(每列一个)。我还将数字转换为float
并删除了\n
。
cols = list(zip(*(map(float, i.replace('\n', '').split(',')[:-1]) for i in lst)))
答案 6 :(得分:1)
正如我从这个问题中理解的那样,需要2D(mx3)数组,它存储数据变量的每个元素。
#creating 2-D Matrix
Matrix = [[0 for x in range(0,3)] for y in range(0,len(data))]
for x in data :
a1=x.split(",") #split each element
for i in range(0,len(data)):
for j in range(0,3): #removes inserting \n
Matrix[i][j]=a1[j]
print(Matrix)