简体   繁体   中英

When isn't a list a list?

The following code returns a list, eg <class 'list'> in python. Everything I do to access that list fails

indexing list fails, enumerating list fails

example if I just 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. Your issue is likely with a line where s does not contain a list with 2 values. If those values do not exist, then you cannot use them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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