【问题标题】:Python: How to return data from a for loop?Python:如何从 for 循环返回数据?
【发布时间】:2019-05-04 14:33:32
【问题描述】:

我的目标是使用 Dash 创建一个实时图表,显示批处理作业执行重复性任务所需的时间。该图将从批处理作业的日志文件中获取数据,并在其中查找一些特定的单词。

问题是当我想在图表中显示数据时,它只显示第一个值,而不是后面的值。

我希望它位于两个单独的函数中,但由于我对图表有疑问,我现在选择将它放在同一个函数中。

def update_graph():
    specific_word = "help"

    for i,line in enumerate(lines):
        if specific_word in line:

            X.append(int(count))
            Y.append(int(time))

            data = go.Scatter(
                x = list(X),
                y = list(Y),
                name = 'Scatter',
                mode = 'lines+markers'
                )

            return {'data':[data], 
            'layout': go.Layout(xaxis = dict(range=[min(X), max(X)]),
                                yaxis = dict(range=[min(Y), max(Y)]))}

我得到的结果只是日志文件中的第一个值,而不是后面的值。

当我用 print(data) 替换返回行并在终端中执行函数时,我得到了我正在寻找的结果。

提前致谢!

【问题讨论】:

  • 你了解for 循环和return 是如何交互的吗?您的函数将始终在您的 if 条件第一次评估为 True 时返回
  • @aws_apprentice ,我不是 100% 确定它是如何工作的,但这是我的猜测。有没有办法解决这个问题,还是我必须重新制作所有东西?
  • 预期的输出应该是什么样的?
  • 您可以在for循环之前创建一个空列表/数组,在for循环内部创建一个语句,如果正确将它们推入列表/数组,在for循环之后返回列表/数组
  • @aws_apprentice 对于它应该附加到列表的每个值,X =(任务计数),Y =(每个任务之间的时间(毫秒))。但正如我所说,它只附加 X 和 Y 的第一个值... Scatter({ 'mode': 'lines+markers', 'name': 'Scatter', 'x': [1, 2, 3, 4, 5, 6], 'y': [109175, 1190, 1178, 1783, 1641, 1000]

标签: python loops graph plotly plotly-dash


【解决方案1】:

问题是python返回第一个值后退出函数。

您可以将所有想要查看的值添加到列表中并返回:

def update_graph():
    specific_word = "help"
    output = []  # the list output will store all the data
    for i,line in enumerate(lines):
        if specific_word in line:

            X.append(int(count))
            Y.append(int(time))

            data = go.Scatter(
                x = list(X),
                y = list(Y),
                name = 'Scatter',
                mode = 'lines+markers'
                )

            output.append({'data':[data],  #add the values to the list
            'layout': go.Layout(xaxis = dict(range=[min(X), max(X)]),
                                yaxis = dict(range=[min(Y), max(Y)]))})
    return output 

所以你会得到一个列表作为返回值。

您可以遍历列表以获取您想要的任何元素:

thelist = update_graph()

for item in thelist:
    print(item)
    #do whatever you want with the item here

【讨论】:

    【解决方案2】:

    return 语句跳出循环。因此这不允许 for 循环继续执行。 要解决此问题,您可以将数据存储在 for 循环中,并将 return 语句放在函数之外。

    你可以试试这个-

    array_name.append( {'data':[data], 
                'layout': go.Layout(xaxis = dict(range=[min(X), max(X)]),
                                    yaxis = dict(range=[min(Y), max(Y)]))})
    

    【讨论】:

      猜你喜欢
      • 2018-09-07
      • 2021-03-08
      • 2015-12-30
      • 2019-07-31
      • 2021-12-17
      • 1970-01-01
      • 2019-05-01
      • 1970-01-01
      • 2011-07-05
      相关资源
      最近更新 更多