gpt4 book ai didi

python - 将字符串 (csv) 的子列表转换为 float (列表理解)

转载 作者:太空宇宙 更新时间:2023-11-04 02:33:24 27 4
gpt4 key购买 nike

我尝试读取一个 csv 文件,我需要将其转换为 float 列表以进行评估。该列表如下所示:

[['Time [s];17063_X;17063_Y;17063_Z;17064_X;17064_Y;17064_Z;17065_X;17065_Y;17065_Z;17067_X;17067_Y;17067_Z;17068_X;17068_Y;17068_Z'], ['0;0.01952;0.04337;0.0242;0.01151;0.04152;0.03236;0.00015;-0.01679;0.05328;0.02872;0.01717;0.09341;0.01452;0.01489;0.07444'], ['0.00042;0.02188;0.04351;0.02803;0.0062;0.04108;0.03312;-0.00529;-0.01412;0.05167;0.02173;0.01377;0.04098;0.00807;0.00246;0.04354'],...]

但实际上它有超过 17000 个额外的条目。我需要的列表应该是这样的:

[['Time [s]', '17063_X', '17063_Y', '17063_Z', '17064_X', '17064_Y', '17064_Z', '17065_X', '17065_Y', '17065_Z', '17067_X', '17067_Y', '17067_Z', '17068_X', '17068_Y', '17068_Z'], [0, 0.01952, 0.04337, 0.0242, 0.01151, 0.04152, 0.03236, 0.00015, -0.01679, 0.05328, 0.02872, 0.01717, 0.09341, 0.01452, 0.01489, 0.07444], ...]

到目前为止,我设法将单行(列表中的最后一个元素)转化为这种格式,但不是所有列表。这是我到目前为止所得到的:

import csv

with open(filepath, 'r') as f:
reader = csv.reader(f)
data = list(reader)

for j in range(1, len(data)): # this loop does nothing?!
for i in data[j]:
dt = i.split(';')

da = [float(i) for i in dt]
print(da)

输出:

[0.005, 0.0207, 0.02925, 0.02095, 0.02332, 0.04211, 0.02223, 0.0075, -0.01961, 0.05093, 0.02604, 0.00711, 0.06644, 0.00689, -0.00092, 0.04737]  

对于列表理解方面的任何帮助和一些提示,我将不胜感激。谢谢!

最佳答案

您需要将最后两行放在 for 循环中,并检查缩进:

for j in range(1, len(data)):
for i in data[j]:
dt = i.split(';')
da = [float(v) for v in dt]
print(da)

关于python - 将字符串 (csv) 的子列表转换为 float (列表理解),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48537026/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com