更改范围功能中的步长值

时间:2015-10-15 09:58:29

标签: python python-2.7 range

list1 = [1, 2, 3, 4]

我正试图找出一种方法来改变每个打印的步骤值

我尝试了什么

r = 0
for i in range(0, 10, list1[r]):
    print i
    r = r + 1

5 个答案:

答案 0 :(得分:2)

我建议使用while循环为此实现自己的生成器。示例 -

def varied_step_range(start,stop,stepiter):
    step = iter(stepiter)
    while start < stop:
        yield start
        start += next(step)

然后你可以用它作为 -

for i in varied_step_range(start,stop,steplist):
    #Do your logic.

我们执行step = iter(stepiter),以便stepiter可以是任何类型的可迭代。

演示 -

>>> def varied_step_range(start,stop,stepiter):
...     step = iter(stepiter)
...     while start < stop:
...         yield start
...         start += next(step)
... 
>>> for i in varied_step_range(0,10,[1,2,3,4]):
...     print i
... 
0
1
3
6

答案 1 :(得分:1)

考虑到你想要的评论:

>>> [range(0,10, i) for i in list1]
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 2, 4, 6, 8], [0, 3, 6, 9], [0, 4, 8]]

更新: 由于我们在迭代时无法更改range()步骤:

>> for el in list1:
>>>    print range(0, 10, el)

[*0*, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, *2*, 4, 6, 8]
[0, 3, *6*, 9]
[0, 4, 8] (?)

最后一个范围没有元素..

答案 2 :(得分:0)

范围功能不支持此功能。你必须明确地进行迭代。

for elem in list1:
  i += elem
  if i > 10:
    break
  print i

答案 3 :(得分:0)

你必须迭代步骤而不是元素:

index = 0
for i in range(len(your_list)):
    if (index+i)>=len(your_list):
        break
    else:
        print your_list[index+i]
        index = index + i

列表[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]上的输出:

1
2
4
7
11
16

列表["a","b","c","d","e","f","g","h","i"]上的输出:

a
b
d
g

答案 4 :(得分:0)

由于这些问题似乎一遍又一遍地出现,因此这里提供了一个更为通用的解决方案:

class RangeBase:
    def __iter__(self):
        i = self.start
        direction = 1 if self.step >= 0 else -1
        while i * direction < self.stop * direction:
            yield i
            i += self.step

此mixin类可以以服务器方式使用:

class DynamicRange(RangeBase):
    def __init__(self, start, stop, step=1):
        self.start = start
        self.stop = stop
        self.step = step

class StepListRange(RangeBase):
    def __init__(self, start, stop, steps):
        self.start = start
        self.stop = stop
        self.steps = iter(steps)
    @property
    def step(self):
        return next(self.steps)

让我们对其进行测试:

>>> a = DynamicRange(1,111,2)
>>> b = iter(a)
>>> next(b)
1
>>> next(b)
3
>>> next(b)
5
>>> next(b)
7
>>> next(b)
9
>>> next(b)
11
>>> next(b)
13
>>> next(b)
15
>>> a.step=3
>>> next(b)
18
>>> next(b)
21
>>> next(b)
24
>>> next(b)
27
>>> next(b)
30
>>> next(b)
33
>>> next(b)
36
>>> next(b)
39
>>> next(b)
42
>>> next(b)
45
>>> a.step=30
>>> next(b)
75
>>> next(b)
105
>>> next(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

>>> a=StepListRange(1,100,[1,2,3,4,5,6,7,8,9,10,20,30,40])
>>> b=iter(a)
>>> next(b)
1
>>> next(b)
3
>>> next(b)
6
>>> next(b)
10
>>> next(b)
15
>>> next(b)
21
>>> next(b)
28
>>> next(b)
36
>>> next(b)
45
>>> next(b)
55
>>> next(b)
75
>>> next(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>>