索引器:列出索引超出范围和python(使用数组2D)

2024-04-29 04:11:41 发布

您现在位置:Python中文网/ 问答频道 /正文

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:列表索引超出范围)


Tags: theintrueforbylentitlerange
1条回答
网友
1楼 · 发布于 2024-04-29 04:11:41

len()是基于1的,range()是基于0的,所以如果你做了len() - 1,它应该可以工作(但你不需要做所有这些,你可以做for i in title_list)。此外,使用此方法可能会丢失大量数据,请参见下面的列表理解选项:

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

相关问题 更多 >