gpt4 book ai didi

Python cookbook(数据结构与算法)从字典中提取子集的方法示例

转载 作者:qq735679552 更新时间:2022-09-28 22:32:09 26 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章Python cookbook(数据结构与算法)从字典中提取子集的方法示例由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

本文实例讲述了Python从字典中提取子集的方法。分享给大家供大家参考,具体如下:

问题:想创建一个字典,其本身是另一个字典的子集 。

解决方案:利用字典推导式(dictionary comprehension)可轻松解决 。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# example of extracting a subset from a dictionary
from pprint import pprint
prices = {
  'ACME' : 45.23 ,
  'AAPL' : 612.78 ,
  'IBM' : 205.55 ,
  'HPQ' : 37.20 ,
  'FB' : 10.75
}
# Make a dictionary of all prices over 200
p1 = { key:value for key, value in prices.items() if value > 200 }
print ( "All prices over 200" )
pprint(p1)
# Make a dictionary of tech stocks
tech_names = { 'AAPL' , 'IBM' , 'HPQ' , 'MSFT' }
p2 = { key:value for key,value in prices.items() if key in tech_names }
print ( "All techs" )
print (p2)

运行结果:

?
1
2
3
4
All prices over 200
{ 'AAPL' : 612.78 , 'IBM' : 205.55 }
All techs
{ 'AAPL' : 612.78 , 'HPQ' : 37.2 , 'IBM' : 205.55 }

字典推导式的方案清晰且运行起来很快.

(代码摘自《Python Cookbook》) 。

希望本文所述对大家Python程序设计有所帮助.

原文链接:http://www.cnblogs.com/apple2016/p/5747573.html 。

最后此篇关于Python cookbook(数据结构与算法)从字典中提取子集的方法示例的文章就讲到这里了,如果你想了解更多关于Python cookbook(数据结构与算法)从字典中提取子集的方法示例的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com