在Python中使用if语句创建新列表

2024-04-24 23:00:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有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的数字?你知道吗


Tags: toinforifassameprintadds
1条回答
网友
1楼 · 发布于 2024-04-24 23:00:39

不要混淆值和索引。你知道吗

等等。完全不要使用索引。不要预先建立一个列表。只需使用列表理解过滤掉负值

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 = [x for x in biglist if x>0]

结果:

[2, 5, 4, 9, 10, 5, 5, 3, 2, 3, 8, 8, 6, 8, 4, 6, 7, 5, 9, 10, 2, 13, 1, 5, 2, 6, 7, 3, 2, 8, 7, 9, 2, 5, 5, 6]

注意,您不需要添加元素来过滤它们。使用itertools.chain避免构建大列表:

import itertools

newlist02 = [x for x in itertools.chain(list01,list02,list03) if x>0]

结果与上面相同,但是如果不需要,我们保存了biglist的创建。你知道吗

相关问题 更多 >