Skip to main content
 首页 » 编程设计

python之你如何迭代一个列表来执行一些将单个元素变成多个元素的操作

2025年04月02日8unruledboy

我有一个来自 LiDAR 传感器的数据的 csv 文件,看起来像这样,但还有数十亿行:

scan_0,scan_1,scan_2 
timestamp_0,timestamp_1,timestamp_2 
7900200,7900225,7900250 
logTime_0,logTime_1,logTime_2 
27:46.8,27:46.8,27:46.8 
distance_0,distance_0,distance_0 
132,141,139 
136,141,155 
139,141,155 
138,143,155 
138,143,142 
139,143,136 
138,143,136 

这是来自平面传感器的数据。所以 Scan_0 是一个时间戳特定扫描的列表或“径向”坐标。

我的计划是:

  1. 将 CSV 文件读入列表
  2. 转置列表
  3. 将 row 的每个元素转换为 xyz 格式,如下例所示。

    scan_0 -----> scan_0 
    timestamp_0-> timestamp_0 
    7900200-----> 7900200 
    logTime_0---> logTime_0 
    27:46.8-----> 27:46.8 
    distance_0--> distance_0 
    132---------> [132*cos(1),132*sin(1),7900200] 
    136---------> [136*cos(2),136*sin(2),7900200] 
    139---------> [139*cos(3),139*sin(3),7900200] 
    138--------->          .          . 
    138--------->          .          . 
    139--------->          .          . 
    138---------> [138*cos(7),139*sin(7),7900200] 
    
  4. 将 xyz 坐标数组写入一个新的 csv 文件,每行一个坐标'

  5. 最终使用轨迹代替来自另一个 csv 文件的 z 坐标的时间戳。

我告诉你所有这些,所以你对我的动机有一些背景。

这是我目前所拥有的:

import csv  
import numpy 
from numpy import genfromtxt 
from numpy import vsplit 
import math 
 
with open('2016_09_16_14_29_09_953.csv',"r") as f: 
    reader = csv.reader(f,delimiter = ",") 
    data = list(reader) 
    row_count = len(data) 
print row_count 
with open("out.csv", "a") as f1: 
    my_r = genfromtxt('2016_09_16_14_29_09_953.csv', delimiter=',', skip_header=6, autostrip=True) #import data 
    my_r = my_r.T #transpose 
    for x in my_r: 
        i=0 
        while i < row_count/360: 
            x = [x*math.cos(i), x*math.sin(i), i] 
            i = i + row_count/360 
 
    thedatawriter = csv.writer(f1) #setup writer 
    for row in my_r: #write the data 
        thedatawriter.writerow(row) 

所有这一切确实会输出源文件的转置。看来我无法将列表中的单个条目变成列表本身。我在这里做错了什么?非常感谢任何帮助、建议和指导。

请您参考如下方法:

您遇到的问题是您正在尝试为未引用数组的变量分配新值。

所以你有

for x in my_r: 
    i=0 
    while i < row_count/360: 
        x = [x*math.cos(i), x*math.sin(i), i] 
        i = i + row_count/360 

你不能这样做,因为 x 不是 my_r 列表的实际元素(更改 x 不会导致更改 my_r 上的元素) .

最简单的方法是创建新数组来存储所需的值。

my_r = genfromtxt('2016_09_16_14_29_09_953.csv', delimiter=',', skip_header=6, autostrip=True) #import data 
my_r = my_r.T #transpose 
new_r = [] 
for x in my_r: 
    i=0 
    while i < row_count/360: 
        new_r.append([x*math.cos(i), x*math.sin(i), i]) 
        i = i + row_count/360 
thedatawriter = csv.writer(f1) #setup writer 
for row in new_r: #write the data 
    thedatawriter.writerow(row)