l = [(2, 2), (3, 4), (4, 1), (1, 3)]
l.sort(key=lambda x: x[1], reverse=True) # 按照元祖的第二个元素排序(降序)
print(l)
# [(3, 4), (1, 3), (2, 2), (4, 1)]
def sorted(*args, **kwargs): # real signature unknown
"""
Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customize the sort order, and the
reverse flag can be set to request the result in descending order.
"""
pass
list = [1,5,7,2,4]
sorted(list)
Out[87]: [1, 2, 4, 5, 7]
#可以设定时候排序方式,默认从小到大,设定reverse = False 可以从大到小
sorted(list,reverse=False)
#Out[88]: [1, 2, 4, 5, 7]
sorted(list,reverse=True)
#Out[89]: [7, 5, 4, 2, 1]
#使用key,默认搭配lambda函数使用
sorted(chars,key=lambda x:len(x))
#Out[92]: ['a', 'is', 'boy', 'bruce', 'handsome']
sorted(chars,key=lambda x:len(x),reverse= True)
#Out[93]: ['handsome', 'bruce', 'boy', 'is', 'a']
tuple_list = [('A', 1,5), ('B', 3,2), ('C', 2,6)]
#key=lambda x: x[1]中可以任意选定x中可选的位置进行排序
sorted(tuple_list, key=lambda x: x[1])
#Out[94]: [('A', 1, 5), ('C', 2, 6), ('B', 3, 2)]
sorted(tuple_list, key=lambda x: x[0])
#Out[95]: [('A', 1, 5), ('B', 3, 2), ('C', 2, 6)]
sorted(tuple_list, key=lambda x: x[2])
#Out[96]: [('B', 3, 2), ('A', 1, 5), ('C', 2, 6)]
python的map 函数使得函数能直接以list的每个元素作为参数传递到funcname中, 并返回响应的新的list
#例: 返回某个list中的所有int数据
def sq(x):
return x*x #求x的平方
map(sq, [1,3, 5,7,9]) #[1, 9, 25, 49, 81]
map(lambda x:x**2,[1,2,3,4])
filter(function or None, iterable) --> filter object
Return an iterator yielding those items of iterable for which function(item)
is true. If function is None, return the items that are true.
执行过程依次将list中的元素传递到funcname函数中, 根据funcname返回的True或False 保留或丢弃元素
from functools import reduce
#例: 返回某个list中的所有int数据
def is_int(x):
if isinstance(x, (int)):
return True
else:
return False
filter(is_int, ["Yi",2, "3", 4]) #[2, 4]
def reduce(function, sequence, initial=None): # real signature unknown; restored from __doc__
"""
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
"""
pass
与map相比 , reduce类似于一个聚合类的应用方法, 把list中的参数, 依次传递给funcname, 每次funcname的参数都是上个funcname 执行结果和下一个list中的元素, 所以, funcname 的 参数必须是两个. 从执行过程看, 有点像递归
#例如: 求range(1, 101)(不包括101)的和,
def c_sum(x, y):
return x + y;
reduce(c_sum, range(1,101)) #5050