将 python 列表中的值递增 6,直到达到条件

Increment values in a python list by 6 until it reaches a condition

我正在努力解决这个看似简单的 python 问题。

我需要列表中的 90 个值增加 6(从 120)直到达到 240,一旦达到 240,它应该减少 6 回到 120。这个循环将继续直到达到 90 个值。

x = [30, 36, 42, 48, 54, 60]
e = [120]


for row in range(90):
    if e[row] >= 120 and e[row] != 240:
        e.append(e[row] + 6)
        print(e[row], "1")
    elif e[row] <= 240 and e[row] != 120:
        e.append(e[row] - 6)
        print(e[row])

目前我的代码运行不正常。达到 240 后,它下降到 236。236 满足 >= 120!= 240 条件,所以它回到 240.

任何指导将不胜感激!

我猜你想要这样的东西:

x = [30, 36, 42, 48, 54, 60]
e = [120]
dir = 1

for row in range(90):
    if dir == 1:
        if e[row] >= 240:
            dir = -1
    else:
        if e[row] <= 120:
            dir = 1

    e.append(e[row] + (dir * 6))
    print(e[row])
    print(f'  LENGTH: {len(e)}')


只需将 range 粘合在一起即可实现此目的的一种方法是:

>>> ((list(range(120, 240, 6)) + list(range(240, 120, -6))) * 3)[:90]
[120, 126, 132, 138, 144, 150, 156, 162, 168, 174, 180, 186, 192, 198, 204, 210, 216, 222, 228, 234, 240, 234, 228, 222, 216, 210, 204, 198, 192, 186, 180, 174, 168, 162, 156, 150, 144, 138, 132, 126, 120, 126, 132, 138, 144, 150, 156, 162, 168, 174, 180, 186, 192, 198, 204, 210, 216, 222, 228, 234, 240, 234, 228, 222, 216, 210, 204, 198, 192, 186, 180, 174, 168, 162, 156, 150, 144, 138, 132, 126, 120, 126, 132, 138, 144, 150, 156, 162, 168, 174]

要按照您尝试的方式在循环中构建它,我会将 delta 放在另一个变量中,并且仅在您碰到其中一个边缘时才翻转它,如下所示:

>>> e = [120]
>>> d = 6
>>> for _ in range(89):
...     n = e[-1] + d
...     if n >= 240 or n <= 120:
...         d *= -1
...     e.append(n)
...
>>> e
[120, 126, 132, 138, 144, 150, 156, 162, 168, 174, 180, 186, 192, 198, 204, 210, 216, 222, 228, 234, 240, 234, 228, 222, 216, 210, 204, 198, 192, 186, 180, 174, 168, 162, 156, 150, 144, 138, 132, 126, 120, 126, 132, 138, 144, 150, 156, 162, 168, 174, 180, 186, 192, 198, 204, 210, 216, 222, 228, 234, 240, 234, 228, 222, 216, 210, 204, 198, 192, 186, 180, 174, 168, 162, 156, 150, 144, 138, 132, 126, 120, 126, 132, 138, 144, 150, 156, 162, 168, 174]

您可以使用变量来保存要添加的金额,并在 6-6 之间切换。测试是正还是负就知道检查哪一端了。

e = [120]
increment = 6

for _ in range(90):
    e.append(e[-1] + increment)
    if increment > 0 and e[-1] == 240:
        increment = -6
    elif increment < 0 and e[-1] == 120:
        increment = 6