【问题标题】:how to pull a string from a list of objects in python如何从python中的对象列表中提取字符串
【发布时间】:2021-02-20 02:34:44
【问题描述】:

import os; import time; 

not_command_error = "error: not an command"
empty_error = "error: file empty"

def read(file):
  e = open(file, "r")
  b = e.readlines()
  e.close()
  return b

code_file = "put your code here"

e = read(code_file)
if e == []:
  print("\033[0;37;41m",empty_error)
  time.sleep(90000)
count = len(e)
print(count)
g = 0
l = 0
while True:
  
  l+= 1
  t = open(code_file, "r")
  y = t.readlines(l)
  t.close()
  k = len(y)
  print(y[k])
  u = y[k]
  
  g+= 1
  if count == g:
    
    break

这是我的代码,我得到并索引超出范围错误,有什么帮助吗? 我尝试更改格式,但仍然无法正常工作。 我得到索引超出范围错误,我不使用变量吗?

【问题讨论】:

    标签: python string time


    【解决方案1】:

    这部分代码会抛出一个 index out of range 错误:

    k = len(y)
    print(y[k])
    

    Python 中列表的索引从 0len(x) - 1,因此要访问最后一个元素,k 应该等于 len(y) - 1

    更好(感谢@MarkK!),您可以使用negative indices 访问数组的末尾:

    print(y[-1])
    

    【讨论】:

    • 或者,更好的是y[-1],忘记k
    猜你喜欢
    • 1970-01-01
    • 2018-12-13
    • 1970-01-01
    • 1970-01-01
    • 2013-05-17
    • 1970-01-01
    • 2018-08-02
    • 1970-01-01
    • 2017-12-15
    相关资源
    最近更新 更多