在python中,如何在条件下对列表排序?

在python中,如何在条件下对列表排序?,python,list,sorting,Python,List,Sorting,假设有一个列表[1,9,7,3,6]。我想生成一个新列表,该列表经过排序且小于其中一个整数,例如整数为7,因此新列表应为list: [1,3,6] 试试这个: num = #some number new_list = sorted(old_list)[:sorted(old_list).index(num)] 或替代品 num = 7 somelist = [3,6,7,1,2,8,9,4,5,12] somelist.sort() somelist[:somelist.index(num

假设有一个
列表[1,9,7,3,6]
。我想生成一个新列表,该列表经过排序且小于其中一个整数,例如整数为7,因此新列表应为list:

[1,3,6]
试试这个:

num = #some number
new_list = sorted(old_list)[:sorted(old_list).index(num)]
或替代品

num = 7
somelist = [3,6,7,1,2,8,9,4,5,12]
somelist.sort()
somelist[:somelist.index(num)]

OUTPUT:
[0, 1, 2, 3, 4, 5, 6]
oldList=[1,9,7,3,6]
myInt=7
newList=已排序([x表示旧列表中的x,如果x
这是一个Python的“列表理解”——它查看oldList中的每个元素,并将其添加到newList中,当且仅当它小于您选择的整数时。此外,sorted()方法是Python中的本机方法

下面是一个很好的资源,可用于将来的列表理解:


希望有帮助

您可以使用列表理解来做到这一点:

my_list = [1,9,7,3,6]
result = sorted([x for x in my_list if x < 7])
my_list=[1,9,7,3,6]
结果=排序([x表示我的_列表中的x,如果x<7])

您可以使用列表:

sorted([i for i in [1,9,7,3,6] if i < 7])
sorted([i代表[1,9,7,3,6]中的i,如果i<7])
您还可以使用生成器:

sorted(i for i in [1,9,7,3,6] if i < 7)
排序(如果i<7,则i代表[1,9,7,3,6]中的i)
注意:列表理解版本执行速度快约2倍。

aa=filter(lambda x:x<7[1,9,7,3,6])
aa = filter(lambda x: x < 7, [1,9,7,3,6])
aa.sort()
print aa

OUTPUT:
[1, 3, 6]
aa.sort() 打印aa 输出: [1, 3, 6]
列表有一种排序方法:

old_list = [1,9,7,3,6]
new_list = [x for x in old_list if x < 7]
new_list.sort()
old_list=[1,9,7,3,6]
新的_列表=[x表示旧_列表中的x,如果x<7]
新建_list.sort()

您可以使用如下列表理解

mylist = [11, 16, 9, 6, 3, 15, 1, 18, 7, 10, 13, 5, 12, 2, 0, 4, 19, 14, 17, 8]
[x for x in sorted(mylist) if x<7]

希望这有帮助

您不需要列表理解
new\u list=sorted(如果x
请注意,对于小列表,它只会更快。对于大型发电机,发电机稍微快一点。同样有趣的是,改用filter()总是比较慢。请注意,这是非常低效的:对完整列表(而不是已过滤的列表)进行排序,对其排序两次,然后遍历它以找到要截断它的索引。当然,这只对更大的列表有意义。
mylist = [11, 16, 9, 6, 3, 15, 1, 18, 7, 10, 13, 5, 12, 2, 0, 4, 19, 14, 17, 8]
[x for x in sorted(mylist) if x<7]
[0, 1, 2, 3, 4, 5, 6]