gpt4 book ai didi

python - 使用循环将值保存在数组中

转载 作者:行者123 更新时间:2023-11-30 22:10:08 25 4
gpt4 key购买 nike

我的程序运行完美;然后,它会给我一个错误,指出以下内容:

Traceback (most recent call last):
File "K:\56_CRT\1 PST EEIC\2_Projects\InternetOfTests\Project_Jacob\Full
Program (Testing).py", line 228, in <module>
inputSamplesm[idx] = [data[0], data[1]]
IndexError: list index out of range

我不知道那是什么。我一直在尝试操作数组和索引,但似乎无法解决问题。请指教。在下面找到我的代码:

with open('MagnaDC Set Points.csv', 'r') as csvfile1, open('Amatek Set Points.csv', 'r') as csvfile2:
dataset = csv.reader(csvfile1, csvfile2, delimiter=',')
next(dataset)
rows = list(dataset)
inputSamplesm = np.empty([len(rows), 2], dtype=float)
outputSamplesm = np.empty([1,3], dtype=float)
inputSamplesa = np.empty([len(rows), 2], dtype=float)
outputSamplesa = np.empty([1,3], dtype=float)
testStartTime = time.time()
for idx, data in enumerate(rows):
inputSamplesm[idx] = [data[0], data[1]]
inputSamplesa[idx] = [data[0], data[1]]
s.sendall('VOLT {0}\n'.format(data[0]).encode('utf-8'))
conn.write('VOLT {0}\n'.format(data[0]).encode('utf-8'))
stopTime = testStartTime + int(data[1])
while time.time() < stopTime:
s.sendall('MEAS:VOLT?\n'.encode('utf-8'))
voltm = s.recv(1024)
voltm = float(voltm)

最佳答案

根据 documentation csv 模块的 reader 函数仅接受一个文件描述符来读取内容。当您为函数传递两个文件描述符时,尽管解释器不会引发任何异常,但它会默默地忽略第二个文件并仅解析第一个文件。您可能需要通过一一解析来重新访问代码,并确保两个文件都非空。

演示

文件1.csv

name,age
swadhikar,29

文件2.csv

name,age
elavarasan,29

示例脚本

import csv


with open('file2.csv') as f1, open('file1.csv') as f2:
reader_obj = csv.reader(f1, f2, delimiter=',')
next(reader_obj)
for line in reader_obj:
print(line)

结果

/usr/bin/python3.6 /home/swadhi/PycharmProjects/pyselenium/python/stackoverflow/so_51741056.py
['elavarasan', '29']

您可以使用 csv.reader() 创建两个单独的阅读器引用来解析这两个 csv 文件,并使用 zip 对其进行迭代,如下所示。

import csv


with open('file1.csv') as f1, open('file2.csv') as f2:
f1_reader_obj = csv.reader(f1)
f2_reader_obj = csv.reader(f2)

next(f1_reader_obj)
next(f2_reader_obj)

for file1_line, file2_line in zip(f1_reader_obj, f2_reader_obj):
line1_as_str = ' '.join(file1_line)
line2_as_str = ' '.join(file2_line)
print(line1_as_str)
print(line2_as_str)

结果

/usr/bin/python3.6 /home/swadhi/PycharmProjects/pyselenium/python/stackoverflow/so_51741056.py
swadhikar 29
elavarasan 29

关于python - 使用循环将值保存在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51741056/

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