python 11 -- python数据类型(5)结构数据类型(2)元组、字典

元组

元组可以看成一种特殊的列表,与列表不同的是元组一旦建立就不能改变。既不能改变其中的数据项,也不能 添加和删除数据项。因此,想让一组数据不能改变就把它们放入元组即可(类比const数组)(*不过我觉得列表更像一个栈,只不过这个栈自带一个函数可以让它颠倒顺序···)

元组的基本形式是以圆括号()括起来的数据元素,也可以通过序号来引用其中的元素

示例:

>>> () # create an empty tuple
()
>>> # also can
... tuple()
()
>>> # with one single element
... (1,)
(1,)
>>> # able to create one by simply using comma to seperate two values
... 2,3
(2, 3)
>>> # automatically bond the first number with x,and the second with y
... x,y=4,5
>>> x
4
>>> y
5
>>> x,y=y,x # actually creating a new tuple,with an existing one
>>> x
5
>>> y
4
>>> atpl = (1,2,3)
>>> atpl[1] # call for the '1' position element
2
>>> atpl[1] = 3 # trial to change an element in tuple
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

⚠️:建立只有一个元素的元组,元素后面要有一个“,”

字典(dict)

字典是比较特殊的一种数据类型,字典中每一个成员是以“键:值”的形式存在的

字典是以“{}”包围的,以“键:值”对的形式声明和存在的数据集合。字典是无序的,其成员位置只是象征性的,在字典中通过键来访问,而不是位置(就是哈希表)

  • 键必须独一无二,但值则不必。
  • 键的命名必须是固定的,这意味着不可用变量去赋值他,因为列表是可变的,所以也不能用列表去赋值
  • 值可以取任何数据类型,但必须是不可变的,如字符串,数或元组。

字典的创建

>>> {} # create a new dict
{}
>>> dict() # create a new dict
{}
>>> newdict = {'birthday':9.27,2001:'year'}
>>> newdict
{'birthday': 9.27, 2001: 'year'}
>>> newdict[2001] # use a hash name
'year'

字典操作函数:

字典操作 描述
dic.clear()
dic.copy()
dic.get( k,[default] )
dic.items()
dic.keys()
dic.pop(k)
dic.update(adict)
dic.values()
dic.fromkeys(iter,value)
dic.popitem()
dic.setdefault( k,default )
>>> newdict = {'a':1,'b':2}
>>> newdict 
{'a': 1, 'b': 2}
>>> newdict.get('a')
1
>>> newdict.get('d',0) # trial of getting a non-exist value
0
>>> newdict['d'] # key 'd' does not exist
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'd'
>>> 
>>> newdict.items()
dict_items([('a', 1), ('b', 2)])
>>> newdict.values()
dict_values([1, 2])
>>> 
>>> newdict.update({'b':4})
>>> newdict
{'a': 1, 'b': 4}
>>> newdict.update({'c':3})
>>>
>>> newdict
{'a': 1, 'b': 4, 'c': 3}
>>> newdict.keys()
dict_keys(['a', 'b', 'c'])
>>> newdict.setdefault('a')
1
>>> newdict.setdefault('d',5)
5
>>> newdict
{'a': 1, 'b': 4, 'c': 3, 'd': 5}
>>> newdict.setdefault('e',5)
5
>>> newdict
{'a': 1, 'b': 4, 'c': 3, 'd': 5, 'e': 5}
>>> newdict.pop('d')
5
>>> newdict
{'a': 1, 'b': 4, 'c': 3, 'e': 5}
>>> newdict.popitem()
('e', 5)
>>> newdict
{'a': 1, 'b': 4, 'c': 3}
发布了64 篇原创文章 · 获赞 6 · 访问量 5567

猜你喜欢

转载自blog.csdn.net/weixin_45494811/article/details/104076472