【问题标题】:Create a new list with if statement in Python在 Python 中使用 if 语句创建一个新列表
【发布时间】: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


【解决方案1】:

不要混合值和索引。

等等。根本不要使用索引。并且不要预先建立一个列表。只需使用列表推导过滤掉负值

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,我们会保存它的创建。

【讨论】:

    猜你喜欢
    • 2020-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多