我正在尝试在 python 列表上写一个条件

I'm trying to write a condition on the python list

我尝试编写一个 Python 程序来接受用户提供的从 0 开始到 20 结束的整数列表。所述列表的每个整数要么与前一个相差2,要么是前一个的四倍。 Return 对或错

谁能纠正我写的条件

lst = []

n = int(input("Enter the no of elements in the list :"))

for i in range (0,n):
    elem = int(input("Enter the elements between 0 and 20 : "))
    lst.append(elem)

if elem >= 0 and elem <=20:
    print(lst)
    
for i in elem:
    if (i+1) >= 2(i) or 4(i+1) == i:
        print(True)
else:
    print(False)
arr_len = int(input("Input a length for list: "))

nums = [0] * arr_len
res = [False] * arr_len

for i in range (len(nums)): 
    num = -1
    while not(num >= 0 and num <= 20):
        num = input("Enter the elements between 0 and 20 : ") 
        num = nums[i] = int(num)
        if (num >= 0 and num <= 20):
            print('appended')
        else:
            print('that number is not between 0 and 20')
for i in range(1,len(res)):
    num = nums[i]
    prev_num = nums[i-1]
    if (abs(num-prev_num)) == 2 or prev_num == 4*num: 
        res[i] = True 
for i in range(len(nums)):
    print('i is: ', i , 'nums[i], ', nums[i],
              ', is allowed in array: ', res[i])
res = dict(zip(nums,res))
print(res)

您可以使用 zip 将项目与其后继者配对。这将使您可以比较它们并根据您的要求使用 any() 或 all() 检查您的情况:

if any(abs(a-b)==2 or a*4==b for a,b in zip(lst,lst[1:]):
   print(True) # at least one number pair meets the criteria
else:
   print(False)

if all(abs(a-b)==2 or a*4==b for a,b in zip(lst,lst[1:]):
   print(True) # all numbers meets the criteria
else:
   print(False)