简体   繁体   English

什么时候列表不是列表?

[英]When isn't a list a list?

The following code returns a list, eg <class 'list'> in python.以下代码返回一个列表,例如 Python 中的<class 'list'> Everything I do to access that list fails我为访问该列表所做的一切都失败了

indexing list fails, enumerating list fails索引列表失败,枚举列表失败

example if I just print(s)例如,如果我只是print(s)

['0.5211', '3.1324']

but if I access the indices但如果我访问索引

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

Why can't I access the elements of the list?为什么我不能访问列表的元素?

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]))

You should check what print(s) outputs again.您应该再次检查print(s)输出的内容。 Your issue is likely with a line where s does not contain a list with 2 values.您的问题可能与s不包含具有 2 个值的列表的行有关。 If those values do not exist, then you cannot use them.如果这些值不存在,则不能使用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM