使用 List Comprehension 获取前 n 项

问题描述

我试过了:

x = [1,2,3,4,5,6,7,100,-1]
y = [a for a in x.sort()[0:5]]
print(y)
y = y[0:4]
print(y)

但这不起作用,因为 sort() 不返回排序列表

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-21-d13e11c1e8ab> in <module>
      1 x = [1,-1]
----> 2 y = [a for a in x.sort()[0:5]]
      3 print(y)
      4 y = y[0:4]
      5 print(y)

TypeError: 'nonetype' object is not subscriptable

解决方法

format() 就地对列表进行排序

list.sort() 对列表进行就地排序,改变列表索引,并且 返回 None(就像所有就地操作一样)

所以你必须这样做:

f"SELECT ..."

输出:

.sort()

The difference between .sort() and sorted() in Python

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...