[Python高效编程] - 快速找到多个字典的公共键
2017-11-19 14:40
549 查看
开发环境
Python版本: python3.6调试工具:pycharm 2017.1.3
电脑系统:Windows 10 64位系统
使用随机数生成数据
from random import randint, sample s1 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))} s2 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))} s3 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))} print(s1) print(s2) print(s3)
{'f': 1, 'd': 3, 'e': 4, 'a': 2, 'g': 2} {'b': 1, 'e': 3, 'f': 3, 'g': 3, 'd': 4, 'c': 1} {'e': 3, 'b': 2, 'f': 3, 'c': 3, 'g': 4}
找出公共键
使用迭代方法
from random import randint, sample s1 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))} s2 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))} s3 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))} print(s1) print(s2) print(s3)
res = []
for k in s1:
if k in s2 and k in s3:
res.append(k)
print(res)
{'e': 1, 'a': 1, 'd': 1, 'g': 3} {'a': 2, 'e': 2, 'd': 3, 'c': 4, 'f': 1, 'g': 4} {'a': 1, 'd': 2, 'f': 3, 'b': 4, 'c': 4, 'e': 1} ['e', 'a', 'd']
使用集合操作
from random import randint, sample s1 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))} s2 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))} s3 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))} print(s1) print(s2) print(s3)
# 使用集合操作
res1 = s1.keys() & s2.keys() & s3.keys()
print(res1)
{'c': 2, 'e': 1, 'a': 1, 'g': 2} {'e': 1, 'c': 3, 'b': 4, 'a': 3, 'g': 3} {'g': 1, 'b': 2, 'f': 2, 'a': 4} {'a', 'g'}
使用map函数和reduce函数处理
from functools import reduce
from random import randint, sample s1 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))} s2 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))} s3 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))} print(s1) print(s2) print(s3)
# 使用map函数和reduce函数
res2 = reduce(lambda a,b: a&b, map(dict.keys, [s1, s2, s3]))
print(res2)
{'d': 2, 'c': 2, 'f': 1} {'c': 4, 'e': 3, 'g': 3, 'b': 1, 'd': 3, 'f': 1} {'c': 3, 'b': 4, 'g': 2} {'c'}
相关文章推荐
- python高效编程技巧5(如何快速找到多个字典中的公共键)
- python快速找到多个字典中的公共键
- <27>python学习笔记——如何快速找到多个字典中的的公共键key
- python-3-如何快速找到多个字典中的公共键(key)?
- Python高效编程-快速找出多个字典中的公有键
- python【5】如何快速找到多个字典中的公共键
- python 2-5 如何快速找到多个字典中的(key) viewkeys(集合)/reduce(lambda a,b:a&b,map(d.keys(),[d1,d2])
- python_如何快速找打字典中公共key
- 如何快速找到多个字典中的公共键(key)
- python高效编程技巧1 (如何在列表,字典,集合中根据条件筛选数据)
- [Python高效编程] - 根据字典的大小,对字典中的项排序
- [Python高效编程] - 在列表,字典,集合中根据条件筛选数据
- Python3.6中多个字典中找到公共key
- Python 高效编程技巧实战(2-1)如何在列表,字典, 集合中根据条件筛选数据
- 如何快速找到多个字典中的公共键
- 如何快速找到多个字典中出现的公共键
- python高效编程技巧4(如何根据字典中值的大小,对字典的项进行排序)
- 【慕课网】如何快速找到多个字典中的公共键
- 2-5快速找到多个字典中的公共键
- 《Python 编程快速上手 — 让繁琐工作自动化》读书笔记之【第5章 字典和结构化数据】