【发布时间】:2020-06-07 23:21:39
【问题描述】:
有一个数字列表,其中包含一些随机数。我正在对这些数字应用条件并进行一些计算并将结果值存储在多个列表中。但我面临的唯一问题是我无法在所有列表中存储相同数量的数字。假设如果该列表的条件不满足,那么0 应该在那里,但这在我的程序中没有发生。在我的程序中,数字列表是:number = [10, 9, 14, 17, -2, -3, 18, 25],条件如下:
- 如果 num == 0
- 如果 0
- 如果 12
- 如果 15
- 如果数字 > 20
- 如果数字
多个列表是:
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]
【问题讨论】:
-
您改变方法,对于这样的任务,您可以生成来自具有您强加的细节的特定分布的数字。
-
这就是我要问的,该怎么做?
-
在每个条件之后,您想在每个列表中存储一个数字吗?
-
不要使用多个列表,而是使用字典。
标签: python python-3.x list arraylist