Python列表去重并保持原顺序

1、

mailto = ['cc', 'bbbb', 'afa', 'sss', 'bbbb', 'cc', 'shafa']
addr_to = list(set(mailto))
addr_to.sort(key = mailto.index)

2、

L = [3, 1, 2, 1, 3, 4]
 T = []
for i in L:
     if not i in T:
         T.append(i)
 T
[3, 1, 2, 4]

3、

L = [3, 1, 2, 1, 3, 4]
T = []
 for i,v in enumerate(L):
     if L.index(v) == i:
         T.append(v)
T
[3, 1, 2, 4]

python高级排序:

key参数/函数

从python2.4开始,list.sort()和sorted()函数增加了key参数来指定一个函数,此函数将在每个元素比较前被调用。 例如通过key指定的函数来忽略字符串的大小写:

sorted(“This is a test string from Andrew”.split(), key=str.lower)
[‘a’, ‘Andrew’, ‘from’, ‘is’, ‘string’, ‘test’, ‘This’]

key参数的值为一个函数,此函数只有一个参数且返回一个值用来进行比较。
这个技术是快速的因为key指定的函数将准确地对每个元素调用。更广泛的使用情况是用复杂对象的某些值来对复杂对象的序列排序,例如:

student_tuples = [(‘john’, ‘A’, 15),(‘jane’, ‘B’, 12),(‘dave’, ‘B’, 10),]
sorted(student_tuples, key=lambda student: student[2]) # sort by age
[(‘dave’, ‘B’, 10), (‘jane’, ‘B’, 12), (‘john’, ‘A’, 15)]

>>> class Student:def init(self, name, grade, age):
self.name = name self.grade = grade
self.age = age
def repr(self):
return repr((self.name, self.grade, self.age))
>>> student_objects = [Student(‘john’, ‘A’, 15),Student(‘jane’, ‘B’, 12),Student(‘dave’, ‘B’, 10),]

>>> sorted(student_objects, key=lambda student: student.age) # sort by age
[(‘dave’, ‘B’, 10), (‘jane’, ‘B’, 12), (‘john’, ‘A’, 15)]

Operator 模块函数

上面的key参数的使用非常广泛,因此python提供了一些方便的函数来使得访问方法更加容易和快速。operator模块有itemgetter,attrgetter,从2.6开始还增加了methodcaller方法。
>>> from operator import itemgetter, attrgetter

>>> sorted(student_tuples, key=itemgetter(2))[(‘dave’, ‘B’, 10), (‘jane’, ‘B’, 12), (‘john’, ‘A’, 15)]

>>> sorted(student_objects, key=attrgetter(‘age’))[(‘dave’, ‘B’, 10), (‘jane’, ‘B’, 12), (‘john’, ‘A’, 15)]

operator模块还允许多级的排序,例如,先以grade,然后再以age来排序:
>>> sorted(student_tuples, key=itemgetter(1,2))[(‘john’, ‘A’, 15), (‘dave’, ‘B’, 10), (‘jane’, ‘B’, 12)]

>>> sorted(student_objects, key=attrgetter(‘grade’, ‘age’))[(‘john’, ‘A’, 15), (‘dave’, ‘B’, 10), (‘jane’, ‘B’, 12)]

你可能感兴趣的:(python)