# 列表连接 a = [1,2] b = [3,4] c = a + b # output: [1,2,3,4] c += a # output: [1,2,3,4,1,2]
# 定义字典 dic = {'first': 123, 'second': 567}
# 找出字典中最小/最小值的索引 dic = {'first': 123, 'second': 567} min(dic, key=dic.get) # output: first max(dic, key=dic.get) # output: second
# 字典元素按值排序 d = {'a': 3, 'b': 1, 'c': 2} ## 方法1 sorted([(el, d[el]) for el in d], key=lambda x: x[1]) # output: [('b', 1), ('c', 2), ('a', 3)] ## 方法2 sorted([el for el in d.items()], key=lambda x: x[1]) # output: [('b', 1), ('c', 2), ('a', 3)] ## 方法3 import operator sorted(d.items(), key=operator.itemgetter(1)) # output: [('b', 1), ('c', 2), ('a', 3)]
# 集合元素求和 c = [{'v':1}, {'v':2}, {'v':3}] sum_v = sum(el['v'] for el in c) # output: 6
# 集合映射(map操作) c = [{'v':1}, {'v':2}, {'v':3}] new_c = [{'m':el['v'] * 2} for el in c] # output: [{'m': 2}, {'m': 4}, {'m': 6}] new_c = [{'m':el['v'] * 2} for el in c if el['v'] > 1] # output: [{'m': 4}, {'m': 6}]