超出范围的索引

问题描述:

我正在尝试制作一个程序,它将计算列表号码中的数字,并将在sequence_len数字中搜索10的总和。 在一分钟内得到10,它应该停止。 1.使用此代码我有一个错误。我该怎么办? total = total +(list_n [i + n]) IndexError:列表索引超出范围超出范围的索引

2.我想要第一个停止,如果我找到了一个总和那么。它是写在最后的“休息”,因为我还是应该写i = len(list_n)?

number = 1234 
sequence_len = 2 

list_n=[] 
total=0 
b="false" 
list_t=[] 

for j in str(number): 
    list_n.append(int(j)) 

c=len(list_n) 

for i in list_n: 
    n=0 
    while n<sequence_len: 
     total=total+(list_n[i+n]) 
     n=n+1 
    if total==10: 
     b=true 
     seq=0 
     while seq>sequence_len: 
      list_t.append(list_t[i+seq]) 
      seq=seq+1 
     break 
    else: 
     total=0 
    if b=="true": 
     break 


if b=="false": 
    print "Didn’t find any sequence of size", sequence_len 
else: 
    print "Found a sequence of size", sequence_len ,":", list_t 
+0

我没有明确地得到问题的第二部分。 – thefourtheye

当你说

for i in list_n: 

i将不参考指标,但到列表元素本身。如果你只想指数,

for i in range(len(list_n)): 

len(list_n)会给你的列表的大小和range(len(list_n))会给你一个范围从0开始,以len(list_n) - 1

+0

我改变了它,但它仍然说“total = total +(list_n [i + n])”超出范围 – user2923032

+0

@ user2923032这是因为while循环'while n thefourtheye

+0

是的。那么我能做什么? – user2923032

结束你有几个错误的数字。先用基本的:

b=true 

这需要对True,否则,蟒蛇将寻找true变量。

其次,i实际上包含该迭代(循环)的变量的值。例如:

>>> l = ['a', 'b', 'c'] 
>>> for i in l: print i 
a 
b 
c 

因此,您不能将其用作索引,因为索引必须是整数。所以,你需要做的就是使用enumerate什么,这将产生两个指数价值的tuple,所以像:

for i, var in enumerate(list_n): 
    n = 0 

行动枚举的例子:

>>> var = enumerate([1,6,5,32,1]) 
>>> for x in var: print x 
(0, 1) 
(1, 6) 
(2, 5) 
(3, 32) 
(4, 1) 

而这个说法应该有逻辑问题,我相信:

total = total + (list_n[i + n - 1]) 

如果你想从列表获得的10之数字,你可以使用这个蛮力技术:

>>> list_of_n = [1,0,5,4,2,1,2,3,4,5,6,8,2,7] 
>>> from itertools import combinations 
>>> [var for var in combinations(list_of_n, 2) if sum(var) == 10] 
[(5, 5), (4, 6), (2, 8), (2, 8), (3, 7), (4, 6), (8, 2)] 

所以,如果你想在列表中有10 3号,你会放combinations(list_of_n, 3),而不是combinations(list_of_n, 2)