首页 > 解决方案 > 如何使用 if-else 语句在多个列表中插入相等数量的值?

问题描述

有一个数字列表,其中包含一些随机数。我正在对这些数字应用条件并进行一些计算并将结果值存储在多个列表中。但我面临的唯一问题是我无法在所有列表中存储相同数量的数字。假设如果该列表的条件不满足,那么0应该在那里,但这在我的程序中没有发生。在我的程序中,数字列表是:number = [10, 9, 14, 17, -2, -3, 18, 25],条件如下:

  1. 如果数 == 0
  2. 如果 0 < 数字 <= 12
  3. 如果 12 < 数字 <= 15
  4. 如果 15 < 数字 <= 20
  5. 如果数量 > 20
  6. 如果数字 < 0

多个列表是:

firstList = []
secondList = []
thirdList = []
forthList = []
fifthList = []
sixthList = []

我的方法:

 number = [10, 9, 14, 17, -2, -3, 18, 25]
firstList = []
secondList = []
thirdList = []
forthList = []
fifthList = []
sixthList = []
for num in number:
    if num ==0:
        firstList.append(0)
    else:
        firstList.append(0)

    if 0 < num <= 12:
        cal = num * 2
        secondList.append(cal)
    else:
        secondList.append(0)

    if 12 <= num <= 15:
        cal = num * 2
        cal2 = num * 4
        secondList.append(cal)
        thirdList.append(cal2)
    else:
        thirdList.append(0)
    if 15 < num <= 20:
        cal = num * 2
        cal2 = num * 4
        cal3 = num * 6
        secondList.append(cal)
        thirdList.append(cal2)
        forthList.append(cal3)
    else:
        forthList.append(0)
    if num > 20:
        cal = num * 2
        cal2 = num * 4
        cal3 = num * 6
        cal4 = num * 4
        secondList.append(cal)
        thirdList.append(cal2)
        forthList.append(cal3)
        fifthList.append(cal4)
    else:
        fifthList.append(0)

        if num < 0:
             cal5 = num * 10
             sixthList.append(cal5)
        else:
            sixthList.append(0)

print("list1: " , firstList)
print("list2: " , secondList)
print("list3: " , thirdList)
print("list4: " , forthList)
print("list5: " , fifthList)
print("list6: " , sixthList)

输出:

list1:  [0, 0, 0, 0, 0, 0, 0, 0]
list2:  [20, 18, 0, 28, 0, 34, 0, 0, 0, 36, 0, 50]
list3:  [0, 0, 56, 0, 68, 0, 0, 0, 72, 0, 100]
list4:  [0, 0, 0, 102, 0, 0, 108, 0, 150]
list5:  [0, 0, 0, 0, 0, 0, 0, 200]
list6:  [0, 0, 0, 0, -20, -30, 0]

期望的输出:

list1:  [0, 0, 0, 0, 0, 0, 0, 0]
list2:  [20, 18, 28, 34, 0, 0, 36, 50]
list3:  [0, 0, 56, 68, 0, 0, 72, 100]
list4:  [0, 0, 0, 102, 0, 0, 108, 150]
list5:  [0, 0, 0, 0, 0, 0, 0, 200]
list6:  [0, 0, 0, 0, -20, -30, 0, 0]

标签: pythonpython-3.xlistarraylist

解决方案


尝试这样的事情,使用列表理解。首先关注每个列表,而不是条件。另请注意,else 0如果不满足条件,它将用 0 填充。

numbers = [10, 9, 14, 17, -2, -3, 18, 25]

firstList = [0]*len(numbers)
secondList = [n*2 if n > 0 else 0 for n in numbers]
thirdList = [n*4 if n>=12 else 0 for n in numbers]
fourthList = [n*6 if n>15 else 0 for n in numbers]
fifthList = [n*4 if n>20 else 0 for n in numbers]
sixthList = [n*10 if n<0 else 0 for n in numbers]

print(firstList)
print(secondList)
print(thirdList)
print(fourthList)
print(fifthList)
print(sixthList)

输出:

[0, 0, 0, 0, 0, 0, 0, 0]
[20, 18, 28, 34, 0, 0, 36, 50]
[0, 0, 56, 68, 0, 0, 72, 100]
[0, 0, 0, 102, 0, 0, 108, 150]
[0, 0, 0, 0, 0, 0, 0, 100]
[0, 0, 0, 0, -20, -30, 0, 0]

推荐阅读