IndexError: list index out of range and python(with array 2D) [英] IndexError: list index out of range and python(With array 2D)

查看:23
本文介绍了IndexError: list index out of range and python(with array 2D)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

title_list = [['determined', 'by', 'saturation', 'transfer', '31P', 'NMR'], ['Interactions', 'of', 'the', 'F1', 'ATPase', 'subunits', 'from', 'Escherichia', 'coli', 'detected', 'by', 'the', 'yeast', 'two', 'hybrid', 'system']]
pc_title_list = [[]]
print(title_list[1][0].isalpha() == True)
for i in range(len(title_list)):
  for j in range(len(title_list[i])):
    if (title_list[i][j].isalpha() == True):
      pc_title_list[i].append(title_list[i][j].lower())

现在我要坚持这个(IndexError:list index out of range).

And now i going to stucking in this (IndexError: list index out of range).

推荐答案

len() 从 1 开始,range() 从 0 开始,所以如果你do len() - 1 它应该可以工作,(但你不需要做所有这些,你可以在 title_list 中为 i 执行 ).此外,使用此方法您似乎丢失了很多数据,请参阅下面的列表理解选项:

len() is 1-based and range() is 0-based, so if you do len() - 1 it should work, (but you don't need to do all that, you can jsut do for i in title_list). Also, it looks like you are missing a lot of data using this method, see the list comprehension option below:

title_list = [['determined', 'by', 'saturation', 'transfer', '31P', 'NMR'],
              ['Interactions', 'of', 'the', 'F1', 'ATPase', 'subunits', 'from',
               'Escherichia', 'coli', 'detected', 'by', 'the', 'yeast', 'two',
               'hybrid', 'system']]

pc_title_list = [[]]
print(title_list[1][0].isalpha() == True)
for i in range(len(title_list) - 1):
    for j in range(len(title_list[i]) - 1):
        if (title_list[i][j].isalpha() == True):
            pc_title_list[i].append(title_list[i][j].lower())

print('for loop: ', pc_title_list) # looks like items are missing

# list comprehension version, much more concise
pc_title_list2 = [[j.lower()
                   for j in i
                   if j.isalpha()]
                  for i in title_list]

print('list comprehension: ', pc_title_list2)

输出:

True
for loop:  [['determined', 'by', 'saturation', 'transfer']]
list comprehension:  [['determined', 'by', 'saturation', 'transfer', 'nmr'], ['interactions', 'of', 'the', 'atpase', 'subunits', 'from', 'escherichia', 'coli', 'detected', 'by', 'the', 'yeast', 'two', 'hybrid', 'system']]

这篇关于IndexError: list index out of range and python(with array 2D)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆