简体   繁体   English

如何从 python 中的对象列表中提取字符串

[英]how to pull a string from a list of objects in python


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

this is my code, and I get and index out of range error, any help?这是我的代码,我得到并索引超出范围错误,有什么帮助吗? i tried changing the format and it still didn't work.我尝试更改格式,但仍然无法正常工作。 i get index out of range error, do i not use a variable?我得到索引超出范围错误,我不使用变量吗?

This part of your code will throw an index out of range error:这部分代码将引发索引超出范围错误:

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

Indices for lists in Python go from 0 to len(x) - 1 , so to access the last element, k should equal len(y) - 1 . Python go 中列表的索引从0len(x) - 1 ,因此要访问最后一个元素, k应该等于len(y) - 1

Even better (thanks, @MarkK,), you can use negative indices to access the end of the array:更好的是(感谢@MarkK),您可以使用负索引来访问数组的末尾:

print(y[-1])

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

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