【问题标题】:When isn't a list a list?什么时候列表不是列表?
【发布时间】:2019-07-14 22:12:46
【问题描述】:

以下代码返回一个列表,例如<class 'list'> 在 python 中。我为访问该列表所做的一切都失败了

索引列表失败, 枚举列表失败

例如,如果我只是 print(s)

['0.5211', '3.1324']

但如果我访问索引

Traceback (most recent call last):
  File "parse-epoch.py", line 11, in <module>
    print("losses.add({}, {})".format(s[0], s[1]))
IndexError: list index out of range

为什么我不能访问列表的元素?

import re

with open('epoch.txt', 'r') as f:
    content = f.readlines()

content = [x.strip() for x in content]

for line in content:
    s = re.findall("\d+\.\d+", line)
    #print(s)
    print("losses.add({}, {})".format(s[0], s[1]))

【问题讨论】:

  • 你需要edit并在第6行后面加上epoch.txt的内容,或者只是content的值。请参阅minimal reproducible example 了解更多信息。
  • 请给minimal reproducible example。似乎您有一个 1 元素列表,出于某种原因,您认为它包含 2 个元素。但是,由于您没有为我们提供足够的信息来重现此列表,我们只能猜测问题所在。
  • 您的文件中好像有一个空行
  • 这里是原始数据文件 Epoch [ 1/ 40] | 的示例d_loss:0.8216 | g_loss:1.8973 纪元 [1/ 40] | d_loss:0.8570 | g_loss:1.6021 纪元 [1/ 40] | d_loss: 1.0567 | g_loss:2.6506 纪元 [1/ 40] | d_loss:0.9862 | g_loss:2.5328 纪元 [1/ 40] | d_loss: 1.0159 | g_loss:1.3859 纪元 [1/ 40] | d_loss: 1.0116 | g_loss:1.6647 纪元 [1/ 40] | d_loss:0.9844 | g_loss:1.7330
  • @Thediz 评论不支持预格式化文本。请edit您的问题添加详细信息。

标签: python list


【解决方案1】:

您应该再次检查print(s) 输出的内容。您的问题可能与 s 不包含具有 2 个值的列表的行有关。如果这些值不存在,则不能使用它们。

【讨论】:

  • findall 值总是返回一个列表。我检查了。 Python 是问题
  • @Thediz 用“Python 是问题”你是在声称你在 Python 的列表数据结构实现中发现了一个错误?
  • @Thediz 它总是返回一个列表,是的,但列表的长度可能会有所不同。
猜你喜欢
  • 2014-07-30
  • 2022-01-17
  • 1970-01-01
  • 2011-06-11
  • 2019-08-13
  • 2020-01-13
  • 2010-10-20
  • 2016-07-21
  • 1970-01-01
相关资源
最近更新 更多