[英]List index out of range while counting Python
I have a little problem - I need to iterate through a list of lists (lines in a file) and count how many times the lines begin with six or seven. 我有一点问题 - 我需要遍历一个列表列表(文件中的行)并计算行以六或七行开头的次数。 It was no problem, but I also need to remove the items which repeat themselves, eg if I have this: [6,6,7,7,6], I need to do this out of it: [6,7,6] - it is the number of switches that counts. 这没问题,但我也需要删除重复的项目,例如,如果我有这个:[6,6,7,7,6],我需要这样做:[6,7,6 ] - 它是计数的开关数量。 But somehow the list index is always out of range. 但不知何故,列表索引总是超出范围。 Why? 为什么? Thank you! 谢谢!
def number_of_switches(list):
counter = []
for element in li:
if int(element[0]) == 6 or int(element[0]) == 7: counter.append(element[0])
else: pass
i = 0
for i in (0, len(counter)):
if counter[i] == counter[i+1]: counter.remove(counter[i+1])
print 'number of switches is', len(counter)-1 #the first number doesn't count as switch, hence '-1'
for i in (0, len(counter))
only iterates over two elements: 0, and the length of counter
. for i in (0, len(counter))
只迭代两个元素:0和counter
的长度。 It does not count up from 0 to the length. 它不会从0数到的长度。 For that you need range: 为此你需要范围:
for i in range(len(counter))
However, you should not do that either. 但是,你也不应该这样做。 Think about what happens each time you remove an element: the list is now one shorter, but you are iterating until the end of the original list. 想想每次删除元素时会发生什么:列表现在缩短了一个,但是您要迭代直到原始列表的末尾。 So you will quickly get an IndexError. 所以你很快就会得到一个IndexError。 You need to append the non-matching elements to a new list, rather than removing from the current one. 您需要将不匹配的元素附加到新列表,而不是从当前列表中删除。
You should be doing for i in range(len(counter)):
and also if counter[i] == counter[i+1]:
will give an error in this range. 你应该for i in range(len(counter)):
做for i in range(len(counter)):
并且if counter[i] == counter[i+1]:
将在此范围内给出错误。 You need to handle the end case. 你需要处理最终案例。
This might be a better solution: 这可能是一个更好的解决方案:
def number_of_switches(list):
counter = []
prev = li[0]
for element in range(1, len(li)):
if int(li[element][0]) != prev:
count.append(int(li[element][0]))
print 'number of switches is', len(counter)-1 #the first number doesn't count as switch, hence '-1'
When you write: 当你写:
for i in (0, len(counter)):
That means for in those two values: 0 and len(counter) and, len(counter) is the index out of range. 这意味着在这两个值中:0和len(计数器),len(计数器)是超出范围的索引。 I think you meant: 我想你的意思是:
for i in range(0, len(counter)):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.