gpt4 book ai didi

python - 函数不返回正确的值

转载 作者:太空宇宙 更新时间:2023-11-03 15:21:48 25 4
gpt4 key购买 nike

我在这个问题上被困了几个小时。

我编写了一段 Python 代码来读取和转换文本文件中的数据,一切运行正常。

simulink_robot_motor1=[]
with open('C:\\Users\...\sensor_data.txt',"r") as data_file:
rows=0
for line in data_file:
rows=rows+1
columns=len(line.split(","))
simulink_robot_motor=[[0 for x in range(columns)] for y in range(rows)]
i=0
with open('C:\\Users\...\sensor_data.txt',"r") as data_file:
for line in data_file:
current_line = line.split(",")
current_line = list(map(float, current_line))
simulink_robot_motor[i]=current_line
i=i+1

我对 simulink_robot_motor 变量感兴趣,它具有以下结果:

[[0.0, 3.6],
[1.6e-06, 3.6],
[4.57e-06, 3.6],
[7.67e-06, 3.6],
[1.09e-05, 3.6],
...

现在,我想在函数中使用这段代码。因此,如果我调用该函数,应该返回列表 simulink_robot_motor

def get_matlab_sensor_data():        
simulink_robot_motor1=[]
with open('C:\\Users\...\sensor_data.txt',"r") as data_file:
rows=0
for line in data_file:
rows=rows+1
columns=len(line.split(","))
simulink_robot_motor=[[0 for x in range(columns)] for y in range(rows)]
i=0
with open('C:\\Users\...\sensor_data.txt',"r") as data_file:
for line in data_file:
current_line = line.split(",")
current_line = list(map(float, current_line))
simulink_robot_motor[i]=current_line
i=i+1
return (simulink_robot_motor)

但是如果我运行 get_matlab_sensor_data() 我会得到以下结果:

   [[0, 3.6],
[0, 0],
[0, 0],
[0, 0],
[0, 0],
...

我尝试了较小的数据集,并关闭了科学十进制风格。然而,仍然没有成功。我的循环运行不正常吗?

最佳答案

您的 return 语句的缩进级别不正确,因此它在 for 循环内执行得太快,并且永远不会完成循环。

def get_matlab_sensor_data():        
simulink_robot_motor1=[]
with open('C:\\Users\...\sensor_data.txt',"r") as data_file:
rows=0
for line in data_file:
rows=rows+1
columns=len(line.split(","))
simulink_robot_motor=[[0 for x in range(columns)] for y in range(rows)]
i=0
with open('C:\\Users\...\sensor_data.txt',"r") as data_file:
for line in data_file:
current_line = line.split(",")
current_line = list(map(float, current_line))
simulink_robot_motor[i]=current_line
i=i+1
return (simulink_robot_motor)

此外,您可能不需要缩进第二个 with 语句:

def get_matlab_sensor_data():        
simulink_robot_motor1=[]
with open('C:\\Users\...\sensor_data.txt',"r") as data_file:
rows=0
for line in data_file:
rows=rows+1
columns=len(line.split(","))
simulink_robot_motor=[[0 for x in range(columns)] for y in range(rows)]
i=0
with open('C:\\Users\...\sensor_data.txt',"r") as data_file:
for line in data_file:
current_line = line.split(",")
current_line = list(map(float, current_line))
simulink_robot_motor[i]=current_line
i=i+1
return (simulink_robot_motor)

关于python - 函数不返回正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43477723/

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