Sorting Lists
- sorted(iterable,key=None,reverse=False),does not mutate list, must assign result to a variable(返回新的列表,对所有可迭代的对象均有效)
- sort(key=None,reverse=False)。mutates the list, returns nothing(改变列表), reverse:True反序;False 正序
代码:
warm = ['red','green','orange']
sortedwarm = warm.sort()
print(sortedwarm)
print(warm)
None ['green', 'orange', 'red']
sortwarm = sorted(warm)
print(sortwarm)
print(warm)
['green', 'orange', 'red'] ['green', 'orange', 'red']
Example1:
>>>sorted([1,5,3,2,9])
[1,2,3,5,9]
>>>a=[5,3,2,1,4]
>>>a.sort()
>>>a
[1,2,3,4,5] #若用list.sort()则list本身将被修改
>>>sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
[1,2,3,4,5] #sorted()对所有的可迭代序列都有效
在python2.4开始,list.sort()和sorted()增加key参数来指定一个函数,此函数在每个元素比较前被调用。
Example2:
>>>sorted("This is a test string from Andrew".split(), key=str.lower) #加了key,忽略大小写
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This'] #key=len按照长度进行排序
>>>sorted("This is a test string from Andrew".split()) #未加key,默认大写在前,小写在后
['Andrew', 'This', 'a', 'from', 'is', 'string', 'test']