Python中list对象

2014-11-24 01:19:56 · 作者: · 浏览: 3

list去重


使用内置的set和list的sort函数。


>>>L = [4,3,5,3,2,5]
>>>temp = list(set(L))
>>>print temp
[2,3,4,5]
>>>temp.sort(key = L.index)
>>>print temp
[4,3,5,2]


使用遍历的方法


>>>temp = []
>>>for i in L:
>>> if i not in temp:
>>> L.append(i)


list函数


sort函数


它原地对列表进行排序,sort是使用Python标准的比较检验作为默认值,而且以递增的顺序进行排序。


可以通过传入关键字参数来修改排序行为,这是指定按名称传递的函数调用中特殊的"name=value"语法。在排序中,key参数给出了一个单个参数的函数,它返回在排序中使用的值,reverse参数允许排序按照降序而不是升序进行:


>>>L = {'abc', 'ABD', 'aBe'}
>>>L.sort()
>>>L
['ABD', 'aBe', 'abc']
>>>L.sort(key=str.lower,reverse=True)
>>>L
['aBe','ABD','abc']


列表迭代与解析


[ for k in L if ],表示在列表L中,如果expr2为真,就循环执行expr1语句并产生一个列表,此为列表推导式。


例如:L = [x**2 for x in range(5) if x>3]


推荐阅读: