把列表中的正数和负数分开排列.
lst = [1, -2, 10, -11, 123, -124] lst.sort(key=lambda x: (x < 0, abs(x))) print(lst) [1, 10, 123, -2, -11, -124]
把多维列表转为一维列表
list_1 = [[1, 2], [3, 4, 5], [6, 7], [8], [9]] # function 1 print([i for k in list_1 for i in k]) # function 2 print(sum(list_1, []))
查询列表中相同元素的个数
from collections import Counter a = [1, 1, 1, 1, 1, 2, 2, 2, 3, 4, 4, 4, 5,9] a_count = Counter(a) print(a_count) b = ['hinimix', 'hinimix', 'hinimix', 'reaphix', 'cui', 'reaphix'] b_count = Counter(b) print(b_count)
列表去重
datas =[1,2,3,2,1,4,5,2,5,6,7,8,9,0] datas = list(set(datas)) print(datas)