【发布时间】:2019-06-20 06:17:45
【问题描述】:
我有 4 个列表
list01 = [2,5,4,9,10,-3,5,5,3,-8,0,2,3,8,8,-2,-4,0,6]
list02 = [-7,-3,8,-5,-5,-2,4,6,7,5,9,10,2,13,-12,-4,1,0,5]
list03 = [2,-5,6,7,-2,-3,0,3,0,2,8,7,9,2,0,-2,5,5,6]
biglist = list01 + list02 + list03
如何创建一个名为“newlist02”的新列表,其中包含大于 0 的“biglist”元素?
这是我尝试过的。
ct = 0
for xval in biglist:
if 0 < xval:
ct += 1 # Adds 1 to ct; same as ct = ct + 1
print(ct) # print out the total number of elements that greater than 0.
newlist02 = 36*[0] # create a new list with 36 "0"s
for xval in biglist:
if 0 < xval:
newlist02[xval] = xval # Adds 1 to ct; same as ct = ct + 1
print(newlist02)
我得到的输出是: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 0, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
如何只包含大于 0 的数字?
【问题讨论】:
-
启动一个新列表,遍历list1,对于每个元素,如果元素> 0,则将其附加到新列表中。
-
使用
filter,或列表理解。不需要显式循环。 -
我刚刚发布了我尝试过的内容
标签: python arrays if-statement