如何在Python中找到位于奇数索引处的元素总和 [英] How to find the sum of elements located at odd indices in Python
问题描述
我知道以前有人在这里问过类似的问题,但我的略有不同.我想编写一个函数,它接受一个正整数列表并返回位于奇数索引处的元素的总和.问题是,我只想使用 for 循环或 while 循环.这是我到目前为止所拥有的:
I know a similar question has been asked here before, but mine is slightly different. I want to write a function that takes a list of positive integers and returns the sum of the elements located at the odd indices. The catch is, I want to use only a for loop or a while loop. Here's what I have so far:
def getSumOdds(aList):
for i in range(0, len(aList)):
if i%2 == 0:
pass
if i%2 != 0:
sum = sum + aList[i]
return sum
但是,当我将此代码输入 Python 时,我收到一条错误消息,提示 builtins.UnboundLocalError: local variable 'sum' referenced before assignment.有谁知道找到总和的更好方法或如何修复错误消息?提前致谢.
However, when I enter this code into Python, I get an error saying builtins.UnboundLocalError: local variable 'sum' referenced before assignment. Does anyone know a better way to find the sum or how to fix the error message? Thanks in advance.
推荐答案
您可以使用生成器(或列表推导式):
You can use a generator (or list comprehension for that):
def getSumOdds(aList):
return sum(aList[i] for i in range(1,len(aList),2))
(如果支持索引(list
支持这个)).
(given indexing is supported (a list
supports this)).
或者你可以,比如 @MSeifert 说,使用切片:
or you can, like @MSeifert says, use slicing:
def getSumOdds(aList):
return sum(aList[1::2])
(鉴于支持切片,并非所有集合都这样做)
(given slicing is supported, not all collections do this)
这就是你所需要的:sum
是一个内置函数.
that's all you need: sum
is a builtin function.
如果 aList
是一个生成器(例如你不能访问 i-th 元素),你可以使用 itertools.islice
:
In case aList
is a generator (you cannot access the i-th element for instance), you can use itertools.islice
:
from itertools import islice
def getSumOdds(aList):
return sum(islice(aList,1,None,2))
您也可以将此方法用于列表等(只要aList
是可迭代的).
You can also use this method for lists, etc. (as long as aList
is iterable).
或者 - 再次支持给定索引 - 您可以将其放入 for
循环中:
Or - again given indexing is supported - you can put it in a for
loop:
def getSumOdds(aList):
result = 0
for i in range(1,len(aList),2):
result += aList[i]
return result
这篇关于如何在Python中找到位于奇数索引处的元素总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!