Created
          May 18, 2017 14:28 
        
      - 
      
- 
        Save Everfighting/06358f38b5dbfc8d7ede6eacc2a12849 to your computer and use it in GitHub Desktop. 
    如何快速找到多个字典中出现的公共键
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | from random import randint,sample | |
| s1 = {x: randint(1,4) for x in sample('abcdefg',ranint(3,6))} | |
| s2 = {x: randint(1,4) for x in sample('abcdefg',ranint(3,6))} | |
| s3 = {x: randint(1,4) for x in sample('abcdefg',ranint(3,6))} | |
| # 法一 | |
| res = [] | |
| for k in s1: | |
| if k in s2 and s3: | |
| res.append(k) | |
| # 法二 | |
| s1.viewkeys()&s2.viewkeys()&s3.viewkeys() | |
| ## 法二进阶版 | |
| map(dict.viewkeys,[s1,s2,s3]) | |
| >>> [dict_keys(['a','b','e','f']), | |
| dict_keys(['c','e','g','g']), | |
| dict_keys(['b','e','d','g','f'])] | |
| reduce(lambda a,b:a &b,map(dict.viewkeys,[s1,s2,s3])) | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment