如何创建比包含特定数字的列表

问题描述 投票:0回答:2

如果numlist包含数字列表,请创建一个仅包含数字的新列表那些小于100的数字。

(例如[42,130,7,100,101]变成[42,7])

我尝试过,但是我的输出仅为“ 1,4”

您能帮我这个忙吗,如果您找到另一种方法而不是使用while循环,那就更好了

numlist = [1,4,200,56,78,900,433,555,554]
numlist2 = []
i=0
while numlist[i] < 100:
    numlist2.append(numlist[i])
    i = i+1

print(numlist2)
python list append
2个回答
1
投票

您可能想得太多。只需使用numlist循环遍历for的元素并检查条件即可。不需要整数索引或while

Oneliner:

numlist2 = [x for x in numlist if x < 100]

“传统”

numlist2 = []
for x in numlist:
    if x < 100:
        numlist2.append(x)

1
投票
numlist2 = list(filter(lambda x: x < 100, numlist))
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.