I'm trying to create a function equal to the sum of every other digit in a list. For example, if the list is [0,1,2,3,4,5], the function should equal 5+3+1. How could I do this? My knowledge of Python does not extend much farther than while and for loops. Thanks.
相关问题
- Is there a limit to how many levels you can nest i
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
This is just a list comprehension that only includes elements in
arr
that have an odd index.To illustrate in a traditional
for
loop:Here is a simple one-liner:
In the above code,
L[1::2]
says "get ever second element inL
, starting at index 1"Here is a way to do all the heavy lifting yourself:
Here's another way, using
enumerate
: