使用 List Comprehension 获取前 n 项
Use List Comprehension to get the top n items
我试过了:
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() 不会 return 排序列表
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-21-d13e11c1e8ab> in <module>
1 x = [1,2,3,4,5,6,7,100,-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
.sort()
就地排序列表
list.sort() sorts the list in-place, mutating the list indices, and
returns None (like all in-place operations)
所以你必须这样做:
x = [1,2,3,4,5,6,7,100,-1]
x.sort()
y = [a for a in x[0:5]]
print(y)
y = y[0:4]
print(y)
输出:
[-1, 1, 2, 3, 4]
[-1, 1, 2, 3]
The difference between .sort() and sorted() in Python.
我试过了:
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() 不会 return 排序列表
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-21-d13e11c1e8ab> in <module>
1 x = [1,2,3,4,5,6,7,100,-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
.sort()
就地排序列表
list.sort() sorts the list in-place, mutating the list indices, and returns None (like all in-place operations)
所以你必须这样做:
x = [1,2,3,4,5,6,7,100,-1]
x.sort()
y = [a for a in x[0:5]]
print(y)
y = y[0:4]
print(y)
输出:
[-1, 1, 2, 3, 4]
[-1, 1, 2, 3]
The difference between .sort() and sorted() in Python.