如何在循环中审核列表中的元素

时间:2018-08-23 23:58:45

标签: python list loops

如何确保b中的元素不小于0或大于10?

即当列表b中的5减少到0时,如何使程序增加到1,然后增加1?

a = [2, 5, 7]
b = []
m = True
counter = 1

while m == True:

    for i in a:

        if i >= 5:
            i -= counter
            b.append(i)
        else:
            i += counter
            b.append(i)

        if len(a) == len(b):
            counter += 1
            print(b)
            b.clear()

        if counter == 15:
            m = False

"""
Current output: 
[2, 5, 7]
[3, 4, 6]
[4, 3, 5]
[5, 2, 4]
[6, 1, 3]
[7, 0, 2]
[8, -1, 1]
[9, -2, 0]
[10, -3, -1]
[11, -4, -2]

Expected output:
[2, 5, 7]
[3, 4, 6]
[4, 3, 5]
[5, 2, 4]
[6, 1, 3]
[7, 0, 2]
[8, 1, 1]
[9, 2, 0]
[10, 3, 1]
[9, 4, 2]
"""

1 个答案:

答案 0 :(得分:0)

不确定我是否会完全遵循您的要求,但是下面是获取预期输出的一种方法(我没有遵循您试图对while循环进行的操作,因此我仅根据以下内容进行了15次循环:您的最大计数器值-但您可以对该外部循环执行其他操作。

numbers = [2, 5, 7]
switches = [True, False, False]
output = list()

for _ in range(15):
    for i, number in enumerate(numbers):
        # keep numbers between 0 and 10
        if number == 0:
            switches[i] = True
        elif number == 10:
            switches[i] = False
        # increment or decrement number based on corresponding "switch"    
        if switches[i]:
            number+=1
            output.append(number)
        else:
            number-=1
            output.append(number)
        # print and reset
        if len(output) == len(numbers):
            numbers = output
            output = list()
            print(numbers)

# OUTPUT
# [3, 4, 6]
# [4, 3, 5]
# [5, 2, 4]
# [6, 1, 3]
# [7, 0, 2]
# [8, 1, 1]
# [9, 2, 0]
# [10, 3, 1]
# [9, 4, 2]
# [8, 5, 3]
# [7, 6, 4]
# [6, 7, 5]
# [5, 8, 6]
# [4, 9, 7]
# [3, 10, 8]