简体   繁体   English

python for循环遍历值不在指定的范围内

[英]python for loop cycles through value not in range specified

I have a python code that contains a list dict , where each element is a list of arbitrary size. 我有一个包含列表dict的python代码,其中每个元素都是任意大小的列表。 I am looping over the elements as follows: 我循环遍历元素如下:

for i in range(len(dict)):
    for j in range(1,len(dict[i])):
        str = dict[i][j]

at this point, I get an error saying IndexError: list index out of range . 在这一点上,我得到一个错误说IndexError: list index out of range I am using range(1,len(dict)) because I want to skip the first element of each list in dict . 我正在使用range(1,len(dict))因为我想跳过dict中每个列表的第一个元素。 At the point the error is generated, i=5 , len(dict[5])=2 , so j should be looping over only 1 , but when I check the j value, I get 2 . 在生成错误的那一点, i=5len(dict[5])=2 ,所以j应该只循环1 ,但是当我检查j值时,我得到2 How is this possible? 这怎么可能?

What's even weirder is that when I type the above code in the python console, I get no such error and everything works fine. 甚至更奇怪的是当我在python控制台中输入上面的代码时,我没有得到这样的错误,一切正常。

Edit: the full code is: (note the change from dict to keywords ) 编辑:完整代码是:(注意从dictkeywords的更改)

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

The actual conds and keywords lists are lot longer and being read in from a file, but I just copied and pasted two elements each from the python console. 实际的condskeywords列表要长得多,并且从文件读入,但我只是从python控制台复制并粘贴了两个元素。

Edit 2: printed out i , j , len(dict[i]) , dict[i] in the inner loop. 编辑2:在内循环中打印出ijlen(dict[i])dict[i] The output is too long to put here, but here is a condensed version: 输出太长了,不能放在这里,但这是一个浓缩版本:

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

The line 这条线

ind = [i for i, x in enumerate(match) if x]

changes your i that you use for the outer loop. 更改您用于外循环的i

That btw wouldn't have happened if you used normal Python looping instead of indexed looping: 如果您使用普通的Python循环而不是索引循环,那就不会发生这种情况:

for words in keywords:
    for word in words[1:]:
        for cond in conds:
            word = word.strip().strip("'").strip()
            match = [(word == l) for l in cond]
            ind = [i for i, x in enumerate(match) if x]
            if len(ind) !=0:
                print ind
                print word

Doesn't that also look much nicer and more meaningful? 这不是看起来更好,更有意义吗?

The variable names could be further improved, but I'll leave that up to you as I don't know proper names for your things. 变量名称可以进一步改进,但我会把它留给你,因为我不知道你的东西的名称。

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

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