target_sum = int(input())
arr_list = [int(x) for x in input().split()]
for i in range(len(arr_list)):
sum=0
sum += arr_list[i] + arr_list[i+1]
print(sum)
11 22 33 44 55
33 55 77 99
回溯(最近一次通话最近):文件“ abc.py”,第10行,在
sum += arr_list[i] + arr_list[i+1]
IndexError:列表索引超出范围按任意键继续。 。
答案 0 :(得分:2)
问题在于,在上一次迭代中,您尝试访问不存在的元素。
尝试一下:
target_sum = input()
arr_list = [int(x) for x in target_sum.split(" ")]
for i in range(len(arr_list)-1):
sum = 0
sum = arr_list[i] + arr_list[i+1]
print(sum)
如果需要,可以使条件检查列表的长度是否大于1:
target_sum = input()
arr_list = [int(x) for x in target_sum.split(" ")]
if len(arr_list) < 2:
print("not enougth values")
exit(0)
for i in range(len(arr_list)-1):
sum = 0
sum = arr_list[i] + arr_list[i+1]
print(sum)
如果要在一行上打印结果,可以将end参数添加到打印功能中,如下所示:
for i in range(len(arr_list)-1):
sum = 0
sum = arr_list[i] + arr_list[i+1]
print(sum, end=" ")
答案 1 :(得分:1)
这是典型的一次性错误。
函数式编程(FP)大大减少了这种情况的发生,并使诸如len(lst)
之类的检查变得多余。
在这里,您要对给定列表中的两个相邻元素求和。
在pythonic FP中典型的用法是:
lst = [int(x) for x in input().split()]
[ x + y for x, y in zip(lst, lst[1:]) ]
# input: 11 22 33 44 55
# output: [33, 55, 77, 99]
这里的窍门是使用lst[1:]
生成的lst
移动了1。但是,它比lst
短了1。
zip()
将lst
的每个元素与lst[1:]
中的对应元素配对。 lst
的最后一个元素没有相应的伙伴。但是zip会忽略此类配对。
lst = [11, 22, 33, 44, 55]
zip(lst, lst[1:]) # generates from:
# lst lst[1:]
#
# 11 22
# 22 33
# 33 44
# 44 55
# 55
# "zipping" to ->
[(11, 22),
(22, 33),
(33, 44),
(44, 55)]
# (55, None) -> eliminated, zip stops where the shorter list
# stops
# however, zip() is in python also lazy (similar to map())
# its output is a generator.
# so when you want to inspect it, you have to do list(zip(...))
# to enforce its full execution, as with all generators...
#
# for x, y in [(11, 22), (22, 33), (33, 44), (44, 55)]
# loads each of the pair components on x and y
# and the expression at the beginning of the list-expression
# x + y collects the sum of those.
实际上,从功能上来说,map()
是一种情况。
但是,在python中,您必须使用list()
强制执行
类似于生成器的map()
。
lst = list(map(int, input().split()))
list(map(lambda x, y: x + y, lst, lst[1:]))
# map processes the two lists in parallel similar to zip
# but gives the corresponding elements of each list
# directly to the arguments in the lambda expression/function:
# here to x and y.
11 22 33 44 55
## [33, 55, 77, 99]
因此,通过应用函数式编程,您将更不会遇到此类错误。
答案 2 :(得分:0)
问题是arr_list[i+1]
,当您到达最后一个索引i
时,它将查找不存在的i+1
,因此出错。
有两种解决方法:
1)减小范围range(len(arr_list) -1)
2)使用try / except:
for i in range(len(arr_list)):
try:
sum=0
sum += arr_list[i] + arr_list[i+1]
print(sum)
except IndexError:
pass
3)您可以重新考虑您的策略。例如,我会做这样的事情:
a = arr_list[:-1]
b = arr_list[1:]
for x,y in zip(a,b):
print(x+y)
此外,请注意sum()
是Python函数,最好使用另一个变量名。
答案 3 :(得分:0)
主要问题是,当输入为空格分隔的值时,在int()
上进行input()
强制转换。
您还可以使用单行列表理解来执行求和。
arr_list = [int(x) for x in input().split()]
target_sum = [a+b for a, b in zip(arr_list[0:-1], arr_list[1:])]
target_sum = input() # 11 22 33 44 55
arr_list = [int(x) for x in target_sum.split()]
[a+b for a, b in zip(arr_list[0:-1], arr_list[1:])]
## Output
# [33, 55, 77, 99]