如何遍历字典中的列表,并在Python的for循环中增加一个变量

2024-09-22 16:31:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表,每个位置都有很多数字:

filteredFile = savgol_filter(filesInformationList["file3"], 41, 3)

我有一个函数来查找列表的峰值:

x, y = find_peaks(filteredFile, height=2200, distance=400)

然后我有一个for循环,它遍历所有这些数字并将其相加为一个变量,但由于某种原因,in给了我以下错误:

Traceback (most recent call last):
  File "C:/Users/Duarte Arribas/Desktop/Documentos/fct 2017-2018/pyProjects/pyProject6/short-term/tableScript.py", line 38, in <module>
    sumOfAllValues += float(eachValue[peaksCount])
IndexError: invalid index to scalar variable.

我做错什么了?你知道吗

编辑

for循环(对不起):

for aValue in range(0, len(filteredFile)):
    for eachValue in y["peak_heights"]:
        sumOfAllValues += float(eachValue[peaksCount])
        peaksCount += 1
    count2 += 1

编辑2

数据:

for fileName in glob.glob('*.txt'):
if fileName[0] != ".":
    fileToRead = open(fileName, "r")
    allLines = fileToRead.readlines()
    filesInformationList[f"file{count}"] = []
    for eachLine in allLines:
        if eachLine[0] != "#":
            allLinesSplitted = eachLine.split("\t")
            filesInformationList[f'file{count}'].append(int(allLinesSplitted[3]))
    count += 1
    print(count, "finished")

第一个号码:

2939.53213139, 2303.18006894, 2473.44015882, 2470.17173524,
   2214.78218945, 2520.4469654 , 2383.29599895, 2372.14267638,
   2605.82521052, 2223.27605917, 2338.32117457, 2482.03905057,
   2438.21479995, 2402.16972817, 2405.29826781, 2376.0999171 ,
   2427.362494  , 2395.18081068, 2410.45159038, 2452.26318775,
   2417.66438326, 2411.38387364, 2389.91487412, 2439.28862516,
   2418.97901305, 2383.45172128, 2438.69588551, 2383.71700336,
   2424.22762773, 2451.33888913, 2413.42301148, 2366.29451547

Tags: in编辑列表forcount数字floatfilename
1条回答
网友
1楼 · 发布于 2024-09-22 16:31:51

y['peak_heights']是一系列标量,您可以通过for循环将其解压。但是你用一个整数计数器索引标量。不能索引标量。你知道吗

你可以直接迭代序列。这将使peaksCount冗余:

for eachValue in y['peak_heights']:
    sumOfAllValues += float(eachValue)

这仍然是反模式和非矢量化的。相反,您可以使用pd.Series.sum

sumOfAllValues += y['peak_heights'].sum()

注意:这并不能保证您的程序按预期工作;它只说明了如何克服已识别的特定错误。你知道吗

相关问题 更多 >