我有一个包含列表 dict
的 python 代码,其中每个元素都是一个任意大小的列表。我按如下方式遍历元素:
for i in range(len(dict)):
for j in range(1,len(dict[i])):
str = dict[i][j]
此时,我收到一条错误消息,提示 IndexError: list index out of range
。我正在使用 range(1,len(dict))
因为我想跳过 dict
中每个列表的第一个元素。在产生错误的地方,i=5
,len(dict[5])=2
,所以j
应该只循环1
,但是当我检查 j
值时,我得到了 2
。这怎么可能?
更奇怪的是,当我在 python 控制台中输入上面的代码时,我没有收到这样的错误并且一切正常。
编辑:完整代码是:(注意从 dict
到 keywords
的变化)
import re
conds = [['emerald cryo i&ii,a,01', '40% (v/v) mpd', 'sodium phosphate dibasic', 'citric acid'],['emerald cryo i&ii,a,02', '40% (v/v) ethylene glycol', 'sodium acetate', 'acetic acid'],['emerald cryo i&ii,a,03', '50% (v/v) peg-200', 'citrate', 'na']]
keywords = [["'sodium acetate'", " 'sodium acetate'", " 'na(ac)'", " 'na acetate'", " 'na_acetate'"],["'rbcl+mgcl2'", " 'rbcl+mgcl2 (0.025m each)'"]]
#cycle through elements to see if there is a match to the dictionary
for i in range(len(keywords)):
for j in range(1,len(keywords[i])):
print j
for k in range(len(conds)):
str = keywords[i][j].strip().strip("'").strip() #this is where the error occurs
match = [(str == l) for l in conds[k]]
ind = [i for i, x in enumerate(match) if x]
if len(ind) !=0:
print ind
print str
实际的 conds
和 keywords
列表要长得多,并且是从文件中读取的,但我只是从 python 控制台中分别复制并粘贴了两个元素。
编辑 2:打印出 i
、j
、len(dict[i])
、dict[i]
在内循环中。输出太长,无法放在这里,但这里有一个浓缩版:
0 1 3 ["'potassium acetate'", " 'k(oac)'", " 'potassium acetate'"]
3 1 3 ["'ammonium nitrate'", " '(nh4)2(no)3'", " 'ammonium nitrate'"]
3 1 3 ["'ammonium nitrate'", " '(nh4)2(no)3'", " 'ammonium nitrate'"]
3 1 3 ["'ammonium nitrate'", " '(nh4)2(no)3'", " 'ammonium nitrate'"]
4 1 5 ["'sodium acetate'", " 'sodium acetate'", " 'na(ac)'", " 'na acetate'", " 'na_acetate'"]
4 1 5 ["'sodium acetate'", " 'sodium acetate'", " 'na(ac)'", " 'na acetate'", " 'na_acetate'"]
5 1 2 ["'rbcl+mgcl2'", " 'rbcl+mgcl2 (0.025m each)'"]
4 1 5 ["'sodium acetate'", " 'sodium acetate'", " 'na(ac)'", " 'na acetate'", " 'na_acetate'"]
4 1 5 ["'sodium acetate'", " 'sodium acetate'", " 'na(ac)'", " 'na acetate'", " 'na_acetate'"]
3 1 3 ["'ammonium nitrate'", " '(nh4)2(no)3'", " 'ammonium nitrate'"]
3 1 3 ["'ammonium nitrate'", " '(nh4)2(no)3'", " 'ammonium nitrate'"]
4 1 5 ["'sodium acetate'", " 'sodium acetate'", " 'na(ac)'", " 'na acetate'", " 'na_acetate'"]
[2]
sodium acetate
4 1 5 ["'sodium acetate'", " 'sodium acetate'", " 'na(ac)'", " 'na acetate'", " 'na_acetate'"]
4 1 5 ["'sodium acetate'", " 'sodium acetate'", " 'na(ac)'", " 'na acetate'", " 'na_acetate'"]
5 1 2 ["'rbcl+mgcl2'", " 'rbcl+mgcl2 (0.025m each)'"]
...
5 2 2 ["'rbcl+mgcl2'", " 'rbcl+mgcl2 (0.025m each)'"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "coarseCondEdit.py", line 38, in <module>
str = keywords[i][j].strip().strip("'").strip()
IndexError: list index out of range
我是一名优秀的程序员,十分优秀!