简体   繁体   English

获取错误消息:切片列表时列表索引超出范围?

[英]getting Error msg: List index out of range while slicing a list?

I would like to slice entries from a list index and then insert the sliced entries into a new list f_index .我想从列表index中切片条目,然后将切片条目插入新列表f_index Unfortunately I receive the error message below:不幸的是,我收到以下错误消息:

the list index is out of range.

The counting variable i is stopped at 129 .计数变量 i 在129处停止。 The list index has a total of 973 entries, and i need to slice them all.列表index共有973个条目,我需要将它们全部切片。

Since this is my first question, feel free to give me feedback on how I can ask better questions in the future.由于这是我的第一个问题,请随时给我反馈,告诉我如何在未来提出更好的问题。

The Code编码

f_index = []
i = 0

for eachindex in index:
    
    f_index.append((str(index[i]).split('--')[1].split(';')[0]))
    
    i= i +1 
  
print(f_index)

Output error Output 错误

IndexError                                Traceback (most recent call last)
<ipython-input-154-f0d0c9347c8a> in <module>
      8 for eachindex in index:
      9 
---> 10     f_index.append((str(index[i]).split('--')[1].split(';')[0]))
     11 
     12     i= i +1

IndexError: list index out of range

It seems that your index is not type of iterable object.您的索引似乎不是可迭代 object 的类型。 you can check it by following code:您可以通过以下代码检查它:

>>> from collections.abc import Iterable
>>> isinstance(index , Iterable)

and result will be True/False.结果将是真/假。

strings,arrays,collections,tuples are iterable and number is not iterable, for example:字符串,arrays,collections,元组是可迭代的,数字是不可迭代的,例如:

>>> name = "ali"
>>> isinstance(name, Iterable)
True
>>> number = 12
>>> isinstance(number, Iterable)
False

*Code tested on Python version 3.8.3 *在 Python 版本 3.8.3 上测试的代码

for more information about iterable objects see this .有关可迭代对象的更多信息,请参阅

Is this a job for a nice, pythonic list comprehension?这是一个很好的pythonic列表理解的工作吗?

index = [['ACCO;NUM;ACCO -- Acceptances Outstanding;;'],
         ['ACCRT;NUM;ACCRT -- ARO Accretion Expense;;']]

f_index = [rec[0].split(' -- ')[1].split(';')[0] for rec in index]
print(f_index)

['Acceptances Outstanding', 'ARO Accretion Expense']

Assuming that your index list looks like,假设您的索引list看起来像,

[['ACCO;NUM;ACCO -- Acceptances Outstanding;;'], ['ACCRT;NUM;ACCRT -- ARO Accretion Expense;;'],......]

which means, list of lists while the inner lists are folowing the format:这意味着,列表列表,而内部列表遵循以下格式:

['<letters>;<letters>;<letters> -- <letters> <letters> <letters>;;']
f_index =[]
for inner_list in index:
    temp=inner_list[0].split('--')
    temp=temp[1].split()
    acc,out=temp[0].strip(),temp[1].strip().strip(';;')
    f_index .append([acc,out])

Thanks for all your help.感谢你的帮助。 I have removed the problematic entry manually and now it runs.我已经手动删除了有问题的条目,现在它运行了。

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

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