Welcome to Qi-U Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
623 views
in Technique[技术] by (71.8m points)

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())

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)

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)

Output:

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']]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Qi-U Community for programmer and developer-Open, Learning and Share
...