【问题标题】:How to iterate through a list inside a dictionary, and increment a variable inside the for loop in Python如何遍历字典中的列表,并在 Python 的 for 循环中增加变量
【发布时间】:2018-06-21 11:09:58
【问题描述】:

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

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

我有一个函数可以找到该列表的峰值:

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

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

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

【问题讨论】:

    标签: python list loops dictionary for-loop


    【解决方案1】:

    y['peak_heights'] 是一系列标量,您可以通过for 循环对其进行解包。但随后你 index 标量与整数计数器。你不能索引一个标量。

    您可以直接迭代该系列。这将使peaksCount 变得多余:

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

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

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

    请注意,这并不能保证您的程序按预期工作;它仅阐明了如何克服已识别的特定错误。

    【讨论】:

      猜你喜欢
      • 2015-10-30
      • 2016-02-05
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 2021-04-01
      • 2014-06-27
      • 1970-01-01
      • 2014-11-28
      相关资源
      最近更新 更多