创建奇数索引python的总和 [英] creating sum of odd indexes python

查看:191
本文介绍了创建奇数索引python的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个函数等于列表中每个其他数字的总和。例如,如果列表是[0,1,2,3,4,5],则函数应该等于5 + 3 + 1。我怎么能这样做?我的Python知识并没有比while和for循环更远。谢谢。

解决方案

以下是简单的一行:

  In [37]:L 
Out [37]:[0,1,2,3,4,5]

In [38]:su​​m L [1 :: 2])
Out [38]:9

代码 L [1 :: 2] 表示从第一个索引开始,获取 L / b>

这是一种完成所有繁重工作的方法:

  L = [0,1,2,3,4,5] 
total = 0
在范围内(len(L)):
if i%2:#if this奇数索引
total + = L [i]

这是另一种方法,使用枚举

  L = [0,1,2,3,4, 5] 
total = 0
for i,枚举数(L):
if i%2:
total + = num


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.

解决方案

Here is a simple one-liner:

In [37]: L
Out[37]: [0, 1, 2, 3, 4, 5]

In [38]: sum(L[1::2])
Out[38]: 9

In the above code, L[1::2] says "get ever second element in L, starting at index 1"

Here is a way to do all the heavy lifting yourself:

L = [0, 1, 2, 3, 4, 5]
total = 0
for i in range(len(L)):
    if i%2:  # if this is an odd index
        total += L[i]

Here's another way, using enumerate:

L = [0, 1, 2, 3, 4, 5]
total = 0
for i,num in enumerate(L):
    if i%2:
        total += num

这篇关于创建奇数索引python的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆