python极简代码之检测元素组成是否相同

可以检测两个字符串的组成是不是一样的,可以检测两个列表的元素是否一样,可以检测集合里的元素是否一致,可以检测字典里的值是否一致:

 1 # !usr/bin/env python3
 2 # *-* coding=utf-8 *-*
 3 
 4 from collections import Counter
 5 
 6 def check_element_unique(first,second):
 7     return Counter(first) == Counter(second)
 8 
 9 #检测字符串
10 print(check_element_unique('abcdefg','gfedcba')) #True
11 
12 #检测列表
13 x = ['a','b','c','d','e','f']
14 y = ['b','d','a','c','f','e']
15 print(check_element_unique(x,y)) #True
16 
17 #检测集合
18 p = {'abcd','bdef','cfage'}
19 q = {'abef','bcdb','cfage'}
20 print(check_element_unique(p,q)) #False
21 
22 #检测字典
23 a = {
24     'name':'james',
25     'language':'python',
26     'age':27,
27     'location':'China',
28     }
29 b = {
30     'name':'Juliy',
31     'language':'Php',
32     'age':27,
33     'location':'China',
34     }
35 print(check_element_unique(a,b)) #False
36 
37 '''
38 #可以看看Counter到底返回了啥:
39 print(Counter(x),Counter(y))
40 print(Counter(p),Counter(q))
41 print(Counter(a),Counter(b))
42 '''
原文地址:https://www.cnblogs.com/mafu/p/13131505.html