【问题标题】:Nested For and Try Loop - Main loop doesn't solve嵌套 For 和 Try 循环 - 主循环无法解决
【发布时间】:2019-02-22 10:07:12
【问题描述】:

我的数据是一个列表列表,其中包含 r 行长度不等的数据字符串 - 其中一些是浮点数,但已作为字符串读入。

我想先遍历所有行,然后遍历所有 elements,然后在所述 elements 上应用 try/except 函数来查找字符串的第一个实例在可以转换为浮点数的行中。

当我明确告诉第二个循环应该对哪一行执行操作时,我的代码按预期输出,但是,当我尝试遍历所有行时,它只输出第一行的预期输出,而没有以下行。

预期的输出列表 float_index(长度 = len(data))将是一个列表,其中包含所有行的第一个可转换元素的索引。

这是带有显式行定义输出 [2] 的代码,因为对于第二行,它是可转换为浮点数的第二个元素:

data = [['Mittl.', 'Halleninnenpegel,', 'Volllast', 'Li', '124', '132', '132', '132', '139', '138', '141', '139', '131', '146'],
['Abgaskamin', 'LW', '130', '129', '121', '104', '100', '96', '94', '89', '86', '108']]


row= 1
floats = []
float_index = []
for i in data[row]:
    try:
        floats.append(str(int(float(i))))
        float_index = [data[row].index(floats[0])]
    except:
        pass
print(float_index)

这是循环数据中所有行的代码,但只输出第一行float_index = [4]的预期值,而预期是float_index = [4,2]:

data = [['Mittl.', 'Halleninnenpegel,', 'Volllast', 'Li', '124', '132', '132', '132', '139', '138', '141', '139', '131', '146'],
['Abgaskamin', 'LW', '130', '129', '121', '104', '100', '96', '94', '89', '86', '108']]

floats = []
float_index = []
for r in range(len(data)):
    for i in data[r]:
        try:  
            floats.append(str(int(float(i))))
            float_index = [data[r].index(floats[0])]
        except:
            pass
print(float_index)

floats 列表可能是问题所在 - 它只是将所有可转换元素收集到一个包含一行的长列表中 - 我需要 floats 列表具有相同的方式作为 data,它将所有可转换元素放入新行,以便通过 floats[0] 我找到所有行的第一个元素,但不知何故无法获得我的围绕实现这一目标。

不胜感激,谢谢!

【问题讨论】:

  • 您好,欢迎来到 SO。 “不起作用”是对问题的完全无用的描述,并且您的代码 sn-p 不是正确的 MCVE (stackoverflow.com/help/mcve),因此即使我们尝试过,我们自己也无法重现该问题。请编辑您的帖子(不要在 cmets 中发布)以添加真正的 MCVE(参见上面的链接)和对问题的正确描述(如果结果不正确,请解释如何以及为什么,如果您收到错误,请发布确切的错误消息和完整的回溯)。
  • @Skadam 数据定义为什么?
  • @RachelGallen 我刚刚更新了帖子 - 抱歉,这是我在 SO 上提出的第一个问题。
  • @RachelGallen 我又更新了,现在包含两行数据
  • @RachelGallen 再次更新,现在应该可以运行了! :)

标签: python-3.x loops for-loop try-except


【解决方案1】:

无需遍历每个元素,只要找到第一个元素就跳出循环:

data = [['Mittl.', 'Halleninnenpegel,', 'Volllast', 'Li', '124', '132', '132', '132', '139', '138', '141', '139', '131', '146'],
['Abgaskamin', 'LW', '130', '129', '121', '104', '100', '96', '94', '89', '86', '108']]

floats = []
float_index = []
for lest in data:
    float_temp = None
    float_ind_temp = None
    for el in lest:
        try:
            float_temp = str(int(float(el)))
            floats.append(float_temp)
            float_index_temp = lest.index(float_temp)
            break
        except:
            pass
    float_index.append(float_index_temp)
print(float_index)

【讨论】:

猜你喜欢
  • 2018-07-13
  • 1970-01-01
  • 1970-01-01
  • 2012-02-09
  • 2021-12-11
  • 1970-01-01
  • 1970-01-01
  • 2015-01-28
相关资源
最近更新 更多