Python:for循环中的可变步长

时间:2017-10-25 10:02:21

标签: python for-loop range

我想从数组中获取for循环中的步长值。有点像,

step = [0,1,2,15,3,87] #values in no order  
for i in range(0, len(raw_pkt), step):

应在每次迭代中更新步长值。那有什么解决方法吗?我知道range()期望整数值不是列表。但我想在每次迭代时从列表中获取值。

4 个答案:

答案 0 :(得分:1)

我想你想要的是itertools.accumulate

from itertools import accumulate

for i in accumulate([0,1,2,15,3,87]):
    print(i)

# would print 0 1 3 18 21 108

答案 1 :(得分:1)

step = [0,1,2,15,3,87] #values in no order for i in range(0, len(raw_pkt), step):

laststp = 0

for stp in step:
   for i in range(stp-laststp, len(raw_pkt), stp):
      #do something
      laststp = stp
      break #this should make sure that each step is applied once.

答案 2 :(得分:1)

这是一个简单的解决方案:

for pkt in [raw_pkt[i] for i in step]:
    print pkt

step = [0,1,2,15,3,87]

raw_pkt = [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199]

结果将是

100
101
102
115
103
187

答案 3 :(得分:1)

遍历step

如果您考虑要实现的目标,那么您并不关心list您尝试index,因为step值是固定。因此,即使raw_pkt的长度为一百万,因为您的step列表只有6长度,您只能拥有6 indexes。< / p>

一旦你意识到这一点,代码变得非常简单,你只想iterate超过step值并增加variable。此variable可用于indexlist或其他任何内容,但这并不重要。

这使得代码非常简洁:

step = [0, 1, 2, 15, 3, 87]
i = 0
for s in step:
   i += s
   #code...

为了证明这是有效的,我们可以做一个更容易理解的例子:

step = [0, 1, 2, 4, 1]
l = [5, 6, 3, 6, 2, 7, 3, 1, 8]
i = 0
for s in step:
   i += s
   print(i, l[i])

outputs

0 5
1 6
3 6
7 1
8 8

希望这有帮助!