有时候经常容易忘一些快速的数据实现结构,从此做一些记录。
1. 根据二维数组首元素排序,如下:
data = [[2,3],[5,4],[9,6],[4,7],[8,1]] data.sort(key=lambda x:x[0]) print(data) [[2, 3], [4, 7], [5, 4], [8, 1], [9, 6]]
2.快速去重
def dedupe(items, key=None): """ items: 哈希或者不可哈希的序列 key: 若items为不可哈希的序列(dict等)则需要指定一个函数 """ seen = set() for item in items: val = item if key is None else key(item) if val not in seen: yield item seen.add(val) nums = [1,2,32,2,2,4,3,2,3,42] print(list(dedupe(nums))) # [1, 2, 32, 4, 3, 42] students = [ {"name": "Stanley", "score": 88}, {"name": "Lily", "score": 92}, {"name": "Bob", "score": 91}, {"name": "Well", "score": 80}, {"name": "Bob", "score": 90}, {"name": "Peter", "score": 80} ] deduped_students = list(dedupe(students, key=lambda s: s['name'])) print(deduped_students) """ [{'name': 'Stanley', 'score': 88}, {'name': 'Lily', 'score': 92}, {'name': 'Bob', 'score': 91}, {'name': 'Well', 'score': 80}, {'name': 'Peter', 'score': 80}] # 删除了相同姓名的元素 """ # 删除姓名和分数都相同的元素 deduped_students = list(dedupe(students, key=lambda s: (s['name'], s['score'])))