Python基础学习!容器:列表,元组,字典与集合!(2)

本文是元组 字典与集合的学习笔记!
真滴好多!

在许多地方都可以用元组代替列表,但是元组的方法函数与列表相比要少。
像,append(),insert()这些函数,元组都没有。因为,创建元组就无法修改。
那么,元组又有哪些优点呢?
:元组占用的空间比较少!
:你不会意外修改元组的值!
:可以将元组用作字典的键!
:函数参数是以元组形式传递的!

与列表类似,元组也是由任意类型元素组成。但是,这个元组是不可以改变的。一旦被定义,就无法被增加,删除,修改元素等操作!
因此:元组就像一个常量列表!

()
可以创建一个空列表:
在这里插入图片描述
带逗号的会变成元组:
在这里插入图片描述
但是元素数量大于1之后,就不用在最后留一个逗号啦:
在这里插入图片描述
这个叫做元组解包!:
在这里插入图片描述
tuple():
tuple:元组,数组;
可以将列表转换为元组!

>>> a = ['you','are','beautiful']
>>> tuple(a)
('you', 'are', 'beautiful')#已经变成了一个元组!
>>>

在这里插入图片描述

接下来介绍字典:

在其他语言中,字典可能会被称作*关系型数组,哈希表,哈希图。*
在python中,字典(dictionary)还经常会被简写为:dict.

字典里的键通常是键值对,键通常是字符串!另外还有一些其他类型!
{}:创建字典!

>>> ww =  {}
>>> ww
{}
>>>
>>> ww =  {'key':'open anything',}
>>> ww =  {'key':'open anything',
... 'sky':'light anything',
... 'me':'love everything'
... }
>>> ww
{'key': 'open anything', 'sky': 'light anything', 'me': 'love everything'}
>>> ww =  {'key':'open anything',
... 'earn':'a big car'
... 'ship':'a boat'#看来仅仅可以最后一个不带逗号!
  File "<stdin>", line 3
    'ship':'a boat'
          ^
SyntaxError: invalid syntax

创建字典的时候不强制空格缩进!

dict()函数转换为字典!

>>> lol = [['a','b'],['c','d'],['e','f']]
>>> dict(lol)
{'a': 'b', 'c': 'd', 'e': 'f'}
>>> lol = (['a','b'],['c','d'],['e','f'])
>>> dict(lol)
{'a': 'b', 'c': 'd', 'e': 'f'}
>>> lol = [['a','b'],['c','d'],('e','f')]
>>> dict(lol)
{'a': 'b', 'c': 'd', 'e': 'f'}
>>>

无论是元组包含着列表,还是列表包含着元组。都可以将其转换为字典格式!
有双字符串的时候:

>>> ss = ['a','bc','def']
>>> dict(ss)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 1; 2 is required
>>> eval(ss)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: eval() arg 1 must be a string, bytes or code object
>>>
>>> ss = ['aa','bc','def']
>>> dict(ss)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #2 has length 3; 2 is required
>>> ss = ['a','bc','de']
>>> dict(ss)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 1; 2 is required
>>> ss = ['aa','bc','de']
>>> dict(ss)
{'a': 'a', 'b': 'c', 'd': 'e'}
>>> ss = ['awed','webc','wede']
>>> dict(ss)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 4; 2 is required
>>>

必须是两个字符的字符串才可以直接转换。否则就要:
用eval()函数:https://blog.youkuaiyun.com/weixin_42859280/article/details/84673170
示范使用eval()函数的:
https://blog.youkuaiyun.com/weixin_40894428/article/details/80683137

元组和列表都可以转换为字典:

>>> ss = ['ab','cd','ef']
>>> dict(ss)
{'a': 'b', 'c': 'd', 'e': 'f'}
>>> ww = ('ab','cd','ef')
>>> dict(ww)
{'a': 'b', 'c': 'd', 'e': 'f'}
>>>

在这里插入图片描述
使用key修改字典:

>>> class = {
  File "<stdin>", line 1
    class = {
          ^
SyntaxError: invalid syntax
>>> class1 = {
... class1 = {'ton':'good',
  File "<stdin>", line 2
    class1 = {'ton':'good',
           ^
SyntaxError: invalid syntax
>>> class1 = { 'ton':'good',
...

在这里插入图片描述
在这里插入图片描述
class是python的保留字。所以不能直接用来定义!
接下来进行使用key进行修改:
初始:

>>> class1 = {
... '1':'125',
... '2':'87',
... '3':'98',
... '4':'110',
... '5':'138',
... '6':'88'
... }
>>> class1
{'1': '125', '2': '87', '3': '98', '4': '110', '5': '138', '6': '88'}

修改:

>>> class1['1'] = '150'#都为字符串形式不要忘记添加引号!

结果:

>>> class1
{'1': '150', '2': '87', '3': '98', '4': '110', '5': '138', '6': '88'}
>>>

第一个:‘1’。已经变成了‘150’。
数字类型的修改:
在这里插入图片描述

>>> class3 = {
... 1:123,
... 2:134,
... 3:142,
... 4:145,
... 5:123,
... 6:34,
... 7:99
... }

>>> class3
{1: 123, 2: 134, 3: 142, 4: 145, 5: 123, 6: 34, 7: 99}#可以出现重复的值!
>>>

修改:

>>> class3
{1: 123, 2: 134, 3: 142, 4: 145, 5: 123, 6: 34, 7: 99}
>>> class3[1]=150#修改值为150!
>>> class3
{1: 150, 2: 134, 3: 142, 4: 145, 5: 123, 6: 34, 7: 99}
>>>

在这里插入图片描述
update():可以将一个字典的键值对复制到另外一个字典里面去!
(当出现同样的‘键’时:后者会取代前者!)

>>> ww = {
... '23':'best',
... '24':'better'
... }
>>> ww
{'23': 'best', '24': 'better'}
>>> ss = {
... '23':'good',
... '11':'wise'
... }
>>> ww
{'23': 'best', '24': 'better'}
>>> ss
{'23': 'good', '11': 'wise'}
>>> ww.update(ss)
>>> ww
{'23': 'good', '24': 'better', '11': 'wise'}#这时,ww的‘23’。已经变成了ss里的good!
>>> ss
{'23': 'good', '11': 'wise'}
>>>

del:删除指定键的元素:当然是删除键值对!

>>> ss
{'23': 'good', '11': 'wise'}
>>> del ss[1]#对应的键,而不是位置数。
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 1
>>> del ss['23']#‘23’字符串才是正确的键!
>>> ss
{'11': 'wise'}
>>>

clear():清除所有元素!

>>> ww
{'23': 'good', '24': 'better', '11': 'wise'}
>>> ww.clear()#调用clear()函数!
>>> ww
{}
>>>

in:判断键是否存在于字典中!
是判断

>>> ss = {
... '22':'handsome',
... '33':'rich',
... '44':'fool'
... }
>>> ss
{'22': 'handsome', '33': 'rich', '44': 'fool'}
>>> 'rich' in ss#不是判断值,是判断键!
False
>>> '22' in ss#不是判断值,是判断键!
True
>>>

指定字典名和键,就可以获得对应元素啦!
好基础的用法!

>>> ss
{'22': 'handsome', '33': 'rich', '44': 'fool'}
>>> ss['22']
'handsome'
>>>

也可以用:get()

>>> ss['22']#中括号!
'handsome'
>>> ss.get('22')#小括号!
'handsome'
>>>

一个用中括号,一个用大括号!
keys():获取所有键!

>>> ss
{'22': 'handsome', '33': 'rich', '44': 'fool'}
>>> ss.keys()
dict_keys(['22', '33', '44'])
>>>

python2中,.keys()函数输出结果就是一个列表!
python3,.keys()函数输出结果:dict_keys([‘22’, ‘33’, ‘44’])!
dict_keys([‘22’, ‘33’, ‘44’])转化为列表类型!需要用到list()函数!
在这里插入图片描述

>>> ss.keys()
dict_keys(['22', '33', '44'])
>>> list(ss.keys())
['22', '33', '44']
>>>

上面是:键。
接下来演示值:
同样需要用到list()函数!

>>> ss.values()
dict_values(['handsome', 'rich', 'fool'])
>>> list(ss.values())
['handsome', 'rich', 'fool']
>>>

items():获取所有键值对!

item:
n. 	项目; 条,条款; 一则; 一件商品(或物品);

在这里插入图片描述
用=和copy()复制。没啥说的!
=:

>>> ss
{'22': 'handsome', '33': 'rich', '44': 'fool'}
>>> ss['6'] = 'new'
>>> ss
{'22': 'handsome', '33': 'rich', '44': 'fool', '6': 'new'}
>>>

copy():如果你想留着以前的数据的话!用这个。

>>> old=ss.copy()
>>> ss
{'22': 'handsome', '33': 'rich', '44': 'fool', '6': 'new'}
>>> old
{'22': 'handsome', '33': 'rich', '44': 'fool', '6': 'new'}
>>> ss['99'] = 'love you forever'
>>> ss
{'22': 'handsome', '33': 'rich', '44': 'fool', '6': 'new', '99': 'love you forever'}#新修改的数据!
>>> old
{'22': 'handsome', '33': 'rich', '44': 'fool', '6': 'new'}#以前的数据!
>>>

集合:
{}
等同于键值对,去掉值。只保留键一样!不可重复!小学的知识!
创建空集合:set() 而不是{} 因为元组诞生的比较早,把大括号抢占啦!

>>> a = set()
>>> a
set()
>>>

同样,如果是空集合。也只会用:set()来表示。而不是什么都没有的{ }来表示!
#插入非数字的,需要是字符模式!
集合是无顺序的!

>>> test = {a,1,2,3,4,5}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
>>> test = {'a',1,2,3,4,5}#插入非数字的,需要是字符模式!
>>> test
{1, 2, 3, 4, 'a', 5}#集合是无顺序的!
>>>

set()函数,可以将其它类型(元组,列表,字典)转换为集合!
都是无序的!
字典的话,只会保留键。不会存储值!

>>> set(['abc','key','love'])
{'key', 'abc', 'love'}
>>> set(('big','eye','beautiful'))
{'eye', 'big', 'beautiful'}
>>> set({'a':'big','b':'eye','c':'beautiful'})
{'b', 'a', 'c'}
>>>

使用in测试值是否存在!
有难度啦!出现for in 之类的啦!

>>> drink = {
... '1':{'caff','sugar','cream'},
... '2':{'caff','protein'},
... '3':{'cream','alcohol'},
... '4':{'juice','caff'}
... }
>>> drink
{'1': {'sugar', 'caff', 'cream'}, '2': {'protein', 'caff'}, '3': {'alcohol', 'cream'}, '4': {'caff', 'juice'}}
>>>

找找哪些含有caff:

>>> for name,contents in drink.items():
...  if 'caff' in contents:
...   print(name)
...
1
2
4
>>>

含有caff但是没有sugar的:

>>> for name,contents in drink.items():
...  if 'caff' in contents and not('sugar' in contents):
...   print(name)
...
2
4
>>>

多层筛选,用集合并,交来算更简单!

合并及运算符!:
&:含有的话,返回True,否则返回Flase:
不过要用:{}符号来表示!
有sugar的:

>>> for name,contents in drink.items():
...  if contents & {'sugar'}:
...   print(name)
...
1
>>>

有sugar的,但是没有sugar的:

>>> for name,contents in drink.items():
...  if 'caff' in contents and not contents & {'sugar'}:
...   print(name)
...
2
4
>>>

那就来点简单的小例子:
初始定义:

>>> a = {'key','eat','eye'}
>>> b = {'blue','eat','nose','ear'}

交集:&:

>>> a&b
{'eat'}
>>>

并集:|:

>>> a|b
{'key', 'eye', 'ear', 'nose', 'blue', 'eat'}
>>>

差集:-:

{'key', 'eye'}
>>> b-a
{'blue', 'ear', 'nose'}
>>>

最常见的就是这三个:
交,并,差!
异或集合:^
仅在两个集合里出现一次的!(交集的另一面!)

>>> b^a
{'ear', 'nose', 'key', 'eye', 'blue'}
>>> a^b
{'ear', 'nose', 'key', 'eye', 'blue'}
>>>

子集与真子集:

<=:子集
<:真子集
>:真超集
>=:超集
>>> c = {1,2,3,4}
>>> d = {1,2,3,4,5,6}
>>> c<d#真子集
True
>>> d<c#真子集
False
>>> c<=d#子集
True
>>> d<=c#子集
False
>>> c>d#真超集
False
>>> d>c#真超集
True
>>> c>=d#超集
False
>>> d>=c#超集
True
>>>

列表,元组,字典,集合。总算写好笔记啦。多练才OK呀!
有点难记得呀!

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值