Python之集合和字典

集合

集合是一个无重复元素的集,支持交,差,与等数学运算,大括号和set()均能创建集合,但创建空集合只能用 set(), {} 用于创建空字典

>>> ab = {'python' , 'is' , 'cool'}#创建集合
>>> ab
{'cool', 'is', 'python'}
>>> a= set('python')#创建集合
>>> b= set('cool')
>>> a
{'o', 'n', 'y', 't', 'p', 'h'}
>>> b
{'l', 'o', 'c'}
>>> 'o' in a    #判断o是否在集合中
True
>>> a - b       #a有而b没有的元素
{'n', 'y', 't', 'p', 'h'}
>>> a | b       #存在于a或b中的元素
{'y', 'l', 'o', 'c', 't', 'p', 'n', 'h'}
>>> a & b       #同时存在于a和b中的元素
{'o'}
>>> a ^ b       #存在于a 和b 但不同时存在的元素
{'c', 'l', 'n', 'y', 't', 'p', 'h'}
>>> 

字典

字典中的键必须是不可变类型,比如你不能使用列表作为键

>>> data = {'LiMing':'lenovo', 'ZhangSan':'acer' , 'XiaoZhang':'Apple'}#创建字典
>>> data
{'LiMing': 'lenovo', 'ZhangSan': 'acer', 'XiaoZhang': 'Apple'}
>>> data['XiaoZhang']#用键检索数据
'Apple'
>>> data['xiaowang']= 'xiaomi'#添加键值对
>>> del data['XiaoZhang']
>>> data
{'LiMing': 'lenovo', 'ZhangSan': 'acer', 'xiaowang': 'xiaomi'}
>>> 'LiMing' in data #判断键是否在字典中
True

dict() 可以从包含键值对的元组中创建字典。

>>> dict((('hello','Google'),('hi','siri')))
{'hello': 'Google', 'hi': 'siri'}

item() 方法遍历字典

>>> for x, y in data.items() :
...     print(' {} : {} '.format(x, y))      
... 
 LiMing : lenovo 
 ZhangSan : acer 
 xiaowang : xiaomi 
>>> 

许多时候我们需要往字典中的元素添加数据,我们首先要判断这个元素是否存在,不存在则创建一个默认值。如果在循环里执行这个操作,每次迭代都需要判断一次,降低程序性能。我们可以使用 dict.setdefault(key, default) 更有效率的完成这个事情。

>>> data={}
>>> data.setdefault('language',[]).append('python')
>>> data
{'language': ['python']}
>>> data.setdefault('language',[]).append('c')
>>> data
{'language': ['python', 'c']}
>>> 

尝试索引一个不存在的索引会抛出 KeyError 错误,可以使用 dict.get(key, default) 来索引键,如果键不存在,那么返回指定的 default 值。

>>> data['idiot']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'idiot'
>>> data.get('idiot','no')
'no'

enumerate() 方法可以再遍历列表(或任何序列类型)的同时返回索引值

>>> for x, y in enumerate([1, 3, 5, 7]):
...     print(' {} : {} '.format(x,y))
... 
 0 : 1 
 1 : 3 
 2 : 5 
 3 : 7 
>>> 

zip() 可以同时遍历两个序列类型

>>> a = ['xiaohong', 'xiaoqiang']
>>> b = ['girl', 'boy']
>>> for x, y in zip(a, b):
...     print('{} is {}'.format(x, y))
... 
xiaohong is girl
xiaoqiang is boy
>>> 

以上内容均摘抄自实验楼:https://www.shiyanlou.com/courses/596/labs/2041/document

字典操作:

TablesAre
len(d)right-aligned
d[key]centered
d[key] = valueare neat
key in dReturn True if d has a key key, else False.
key not in dEquivalent to not key in d.
iter(d)Return an iterator over the keys of the dictionary. This is a shortcut for iter(d.keys()).
clear()Remove all items from the dictionary.
copy()Return a shallow copy of the dictionary.
get(key[, default])
items()Return a new view of the dictionary’s items ((key, value) pairs).
keys()Return a new view of the dictionary’s keys. See the documentation of view objects.
pop(key[, default])If key is in the dictionary, remove it and return its value, else return default.
popitem()Remove and return an arbitrary (key, value) pair from the dictionary.
setdefault(key[, default])
values()Return a new view of the dictionary’s values.

The Python Standard Library

字典键排序(3.X):

>>> D = {'a': 1, 'b': 2, 'c': 3}
>>> D
{'b': 2, 'c': 3, 'a': 1}
>>> Ks = D.keys()
# Sorting a view object doesn't work!
>>> Ks.sort()
AttributeError: 'dict_keys' object has no attribute 'sort'
>>> Ks = list(Ks) #强制转换成列表然后排序
>>> Ks.sort()
>>> for k in Ks: print(k, D[k])
...
a 1
b 2
c 3
>>> D
{'b': 2, 'c': 3, 'a': 1}
>>> Ks = D.keys() #或者用sorted()作用于keys,其接受任何可迭代对象
>>> for k in sorted(Ks): print(k, D[k])
...
a 1
b 2
c 3
>>> D
{'b': 2, 'c': 3, 'a': 1}
>>> for k in sorted(D): print(k, D[k]) #或者直接排序字典
...
a 1
b 2
c 3
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
字典集合Python中都是一种数据结构,但它们有一些区别。 首先,字典是由键(key)和值(value)配对组成的元素的集合,而集合是一系列无序的、唯一的元素组合。字典可以通过键来访问对应的值,如果键不存在,则会抛出异常;而集合不支持索引操作,只能通过值来判断元素是否存在。 其次,字典集合的性能表现也有所不同。字典的查找、添加和删除操作都可以在常数时间复杂度内完成,而集合的性能也非常高效。因此,在需要高效地进行查找和去重操作时,字典集合都是很好的选择。 此外,字典集合的内部结构都是一张哈希表,但字典存储了键、值和哈希值这三个元素,而集合内只存储了哈希值。这也是导致字典可以通过键来索引值,而集合不支持索引操作的原因。 综上所述,字典集合的区别在于字典是键值对的集合,支持通过键来访问值,而集合是无序的、唯一的元素组合,不支持索引操作。同时,字典集合在性能上都表现出色,适用于不同的场景。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [Python_数据结构_字典集合的差异对比](https://blog.csdn.net/feizuiku0116/article/details/119777675)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [Python中的字典集合有什么区别?](https://blog.csdn.net/2301_78316786/article/details/131133549)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值