如何根据前一个列表中的某些数字来制作一个单独的列表?

2024-04-23 09:34:08 发布

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

嘿,伙计们想完成我的程序。这是我的密码:

lists = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

#I want to make a new list consisting of only numbers above 50 from that list
if any(list > 50 for list in list):
newlists = list

我不知道怎么做。我做错什么了,有人能帮我吗?你知道吗


Tags: oftofrom程序密码onlynewmake
3条回答

newlist = [x for x in lists if x > 50]

阅读列表理解here

两种选择。使用列表理解:

lst = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
[x for x in lst if x > 50]

在python2.x中使用filter

filter(lambda x: x > 50, lst)

或者在Python 3.x中使用filter,如注释所示,filter在此版本中返回迭代器,如果需要,需要首先将结果转换为列表:

list(filter(lambda x: x > 50, lst))

不管怎样,结果和预期一样:

=> [60, 70, 80, 90, 100]

像这样的方法会奏效:

new_list = [ x for x in lists if x > 50 ]

这被称为“list comprehension”,非常方便。你知道吗

相关问题 更多 >