访问一个元组枚举?

时间:2018-10-03 10:10:26

标签: python list enumerate

我想遍历列表并汇总所有元素。除非数字是5,否则我想跳过数字5之后的数字。例如:

x=[1,2,3,4,5,6,7,5,4,3] #should results in 30

当使用枚举时,我只是不确定如何访问元组的索引。我想做的是使用一条if语句,如果先前索引处的数字== 5,则继续循环。

谢谢

7 个答案:

答案 0 :(得分:4)

itertools documentation有一个名为 pairwise 的食谱。您可以复制粘贴该功能,也可以从more_itertools(需要安装)中导入该功能。

演示:

>>> from more_itertools import pairwise
>>> 
>>> x = [1,2,3,4,5,6,7,5,4,3]
>>> x[0] + sum(m for n, m in pairwise(x) if n != 5)
30

编辑:

  

但是,如果我的数据结构可迭代但不支持索引怎么办?

在这种情况下,上面的解决方案需要进行小的修改。

>>> from itertools import tee
>>> from more_itertools import pairwise
>>> 
>>> x = (n for n in [1,2,3,4,5,6,7,5,4,3]) # generator, no indices!
>>> it1, it2 = tee(x)
>>> next(it1, 0) + sum(m for n, m in pairwise(it2) if n != 5)
30

答案 1 :(得分:3)

x=[1,2,3,4,5,6,7,5,4,3] print(sum(v for i, v in enumerate(x) if (i == 0) or (x[i-1] != 5))) 30 一起使用

例如:

    CREATE TABLE "AP"."SOURCE"     
 (

"RATING" CHAR(30 BYTE), 

 "SUBMISSION_STATUS" CHAR(12 BYTE), 

"UOANAME" CHAR(32 BYTE), 

 "W_INSERT_DT" TIMESTAMP (6), 

"W_UPDATE_DT" TIMESTAMP (6), 

"SCIVAL_CIT_CATEGORY" NUMBER(5,0), 

"TOTAL_AUTHORS" BINARY_DOUBLE, 

"REF2014" CHAR(3 BYTE), 

CONSTRAINT "Submission_Rating_not_valid" 

CHECK ( (Submission_status ='To be scored' and Rating is null)  or 

(Submission_status ='NO' and Rating is null )
     or ( Submission_status = 'Potential' and
       Rating is not null and Rating != 'Not REF Eligible')              

or ( Submission_status ='Yes' and Rating  is not null 
     and Rating != 'Not REF Eligible' )
  or ( Submission_status ='No'
  and Rating  is  not null and Rating != 'Not REF Eligible')
 or  (Submission_status ='No' and Rating = 'Not REF Eligible'
      ) ENABLE

   )
 )

输出:

[rowClass]="rowCallback"

答案 2 :(得分:3)

不喜欢被臭虫缠身的单线而被推崇。

所以这是一个for循环的答案。

x=[1,2,3,4,5,6,7,5,4,3, 5] #should results in 35. 

s = 0
for i, v in enumerate(x):
    if i != 0 and x[i-1] == 5: 
        continue 
    s += v

print(s)

答案 3 :(得分:2)

简单,冗长的方式:

SKIP_PREV = 5
x = [1,2,3,4,5,6,7,5,4,3]
prev = -1
s = 0
for num in x:
    if prev != SKIP_PREV:
        s += num
    prev = num
print(s)
# 30

紧凑,也许不太清楚:

SKIP_PREV = 5
x = [1,2,3,4,5,6,7,5,4,3]
s = sum(num for i, num in enumerate(x) if i == 0 or x[i - 1] != SKIP_PREV)
print(s)
# 30

答案 4 :(得分:1)

如果您愿意使用第三方库,则可以将NumPy与整数索引一起使用:

import numpy as np

x = np.array([1,2,3,4,5,6,7,5,4,3])

res = x.sum() - x[np.where(x == 5)[0]+1].sum()  # 30

另请参阅What are the advantages of NumPy over regular Python lists?

答案 5 :(得分:0)

您可以将列表与本身的移位版本配对。这应该起作用:

sum(val for (prev, val)
    in zip(itertools.chain((None,), x), x)
    if prev != 5 )

答案 6 :(得分:0)

迄今为止最长的代码。无论如何,它不需要枚举,它是一个简单的FSM

x = [1,2,3,4,5,6,7,5,4,3]
skip = False
s = 0 
for v in x:
    if skip:
        skip = False
    else:
        s += v
        skip = v == 5
print(s)