list_test = [ [ [1,2,3], [4,5,6] ], [ [1,3,4], [7,8,9], [1,3,3] ] ] result = [x for i in list_test for j in i for x in j] result输出结果:
[1, 2, 3, 4, 5, 6, 1, 3, 4, 7, 8, 9, 1, 3, 3]使用:
from collections import Counter from collections import Iterable counter_result = Counter(result) counter_result # 从输出结果中可以看出来1出现了3次,2出现了1次,3出现了4次。。。。。。输出结果:
Counter({1: 3, 2: 1, 3: 4, 4: 2, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1})items使用:
counter_result.items() # 将字典编程元祖结构输出结果:
dict_items([(1, 3), (2, 1), (3, 4), (4, 2), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1)])判断类型:
print('是否是可迭代对象n', isinstance(counter_result.items(), Iterable)) # print('typen', type(counter_result.items())) for i in counter_result.items(): print(i)输出结果:
是否是可迭代对象 True (1, 3) (2, 1) (3, 4) (4, 2) (5, 1) (6, 1) (7, 1) (8, 1) (9, 1)sort 自定义使用:
sorted(counter_result.items(), key = lambda x: x[1], reverse=True)输出结果:
[(3, 4), (1, 3), (4, 2), (2, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1)]分析:
# 根据元祖中的第二个的大小进行排序,key就是指定排序规则,默认升序 sorted(counter_result.items(), key = lambda x: x[1])输出结果:
[(2, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (4, 2), (1, 3), (3, 4)]
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)