1 元组
列表非常适合用于存储在程序运行期间可能变化的数据集。列表是可以修改的。然而,有时候需要创建一系列不可修改的元素,元组可以满足这种需求。Python将不能修改的值称为不可变的,而不可变的列表被称为元组 。
1.1 元组的定义
元组(tuple):元组与列表类似,不同之处在于元组的元素不能修改。在Python中,用圆括号(( ))来表示元组,并用逗号来分隔其中的元素。
# 元组
('trek', 'cannondale', 'redline', 'specialized')
(1, 2, 3)
注意:元组元素是不可修改的,当我们尝试修改元组中的元素时,会返回类型错误消息:
In [1]: dimensions = (1, 2, 3)
In [2]: dimensions[0] = 4
Out[2]: Traceback (most recent call last):
File "C:/Users/Sussurro/Desktop/pythonProject/Test.py", line 2, in <module>
dimensions[0] = 4
TypeError: 'tuple' object does not support item assignment
可以使用索引访问一个元组中指定位置的元素,索引计数从 0 开始(顺序索引)。此外Python还支持倒序索引,最右边的索引值是 -1,从右到左依次递减。
In [1]: bicycles = ('trek', 'cannondale', 'redline', 'specialized')
In [2]: print(bicycles[0]) # return trek
In [3]: print(bicycles[-2]) # return redline
可以使用 for 遍历元组中的每一个元素。
In [1]: bicycles = ('trek', 'cannondale', 'redline', 'specialized')
In [2]: for bicycle in bicycles:
In [3]: print(bicycle)
注意:元组中只包含一个元素的时候,需要在元素后面添加逗号。
In [1]: dimensions = (1, )
In [2]: print(type(dimensions)) # return <class 'tuple'>
In [1]: dimensions = (1)
In [2]: print(type(dimensions)) # return <class 'int'>
In [1]: dimensions = [1]
In [2]: print(type(dimensions)) # return <class 'list'>
1.2 元组的常用操作
1)方法
2)列表与元组的转换
使用 list( ) 函数可以把元组转换成列表;使用 tuple( ) 函数可以把列表转换成元组。
In [1]: dimensions = (1, 2, 3)
In [2]: print(list(dimensions)) # return [1, 2, 3]
In [1]: dimensions = [1, 2, 3]
In [2]: print(tuple(dimensions)) # return (1, 2, 3)
3)元组的应用场景
函数的参数和返回值,—个函数可以接收多个参数,或者返回多个数据(此时括号可以省略);
格式化字符串后面的 ( ) 本质上就是一个元组;
让列表不可以被修改,以保护数据安全;
2 字典
2.1 字典的定义
(参考链接:映射类型 — dict)
字典(dict):字典是一系列 键-值 对,通常用于存储描述同一个物体的相关信息。每个键(key)都与一个值(value)相关联,可以使用键来访问与之相关联的值。与键相关联的值可以是数字、字符串、列表乃至字典。事实上,可将任何Python对象用作字典中的值,但键只能使用字符串、数字或者元组。在Python中,字典用放在花括号({ })中的一系列键-值对表示。键和值之间用冒号分隔,而键-值对之间用逗号分隔。在字典中,你想存储多少个键-值对都可以。
# 字典
xiaoming = {"name": "小明", "age": 18, "height": 1.75}
键-值对是两个相关联的值。指定键时,Python将返回与之相关联的值。(列表是有序的对象集合,字典是无序的对象集合)
In [1]: xiaoming = {"name": "小明", "age": 18, "height": 1.75}
In [2]: print(xiaoming['age']) # return 18
2.2 字典的常用操作
1)修改字典中的值
要修改字典中的值,可依次指定字典名、用方括号括起的键以及与该键相关联的新值。
字典[键] = 新值
例如:
In [1]: xiaoming = {"name": "小明", "age": 18, "height": 1.75}
In [2]: xiaoming['age'] = 20
In [3]: print(xiaoming) # return {'name': '小明', 'age': 20, 'height': 1.75}
2)添加键值对
字典是一种动态结构,可随时在其中添加键值对。要添加键值对,可依次指定字典名、用方括号括起的键和相关联的值。
字典[键] = 值
例如:
In [1]: xiaoming = {"name": "小明", "age": 18, "height": 1.75}
In [2]: xiaoming['weight'] = 135
In [3]: xiaoming['gender'] = 'man'
In [4]: print(xiaoming) # return {'name': '小明', 'age': 18, 'height': 1.75, 'weight': 135, 'gender': 'man'}
注意:键值对的排列顺序与添加顺序可能不同。Python不关心键值对的添加顺序,而只关心键和值之间的关联关系(无序)。
方法 | 描述 |
---|---|
dict.setdefault(key[, default]) | 如果字典存在键 key,返回它的值。如果不存在,插入值为 default 的键 key,并返回 default 。default 默认为 None。 |
dict.update([other]) | 使用来自 other 的键/值对更新字典,覆盖原有的键。返回 None。 \newline update() 接受另一个字典对象,或者一个包含键/值对(以长度为二的元组或其他可迭代对象表示)的可迭代对象。 \newline 如果给出了关键字参数,则会以其所指定的键/值对更新字典。 |
例如:
In [1]: xiaoming = {"name": "小明", "age": 18, "height": 1.75}
In [2]: print(xiaoming.setdefault('weight', 135)) # return 135
In [3]: print(xiaoming) # return {'name': '小明', 'age': 18, 'height': 1.75, 'weight': 135}
In [1]: xiaoming = {"name": "小明", "age": 18, "height": 1.75}
In [2]: newxiaoming = {'age': 20, 'weight': 135}
In [3]: xiaoming.update(newxiaoming)
In [4]: print(xiaoming) # return {'name': '小明', 'age': 20, 'height': 1.75, 'weight': 135}
In [5]: xiaoming.update(age=20, weight=135)
In [6]: print(xiaoming) # return {'name': '小明', 'age': 20, 'height': 1.75, 'weight': 135}
3)删除键值对
语句 | 描述 |
---|---|
del dict[key] | 从字典中删除键 key 及其对应的值 |
例如:
In [1]: xiaoming = {"name": "小明", "age": 18, "height": 1.75}
In [2]: del xiaoming['name']
In [3]: print(xiaoming) # return {'age': 18, 'height': 1.75}
方法 | 描述 |
---|---|
dict.pop(key[, default]) | 如果 key 存在于字典中则将其移除并返回其值,否则返回 default。 \newline 如果 default 未给出且 key 不存在于字典中,则会引发 KeyError。 |
dict.popitem() | 从字典中移除并返回一个 (键, 值) 对。 键值对会按 LIFO (后进先出)的顺序被返回。 |
dict.clear() | 移除字典中的所有元素。 |
例如:
In [1]: xiaoming = {"name": "小明", "age": 18, "height": 1.75}
In [2]: print(xiaoming.pop('name')) # return 小明
In [3]: print(xiaoming) # return {'age': 18, 'height': 1.75}
In [1]: xiaoming = {"name": "小明", "age": 18, "height": 1.75}
In [2]: print(xiaoming.popitem()) # return ('height', 1.75)
In [3]: print(xiaoming) # return {'name': '小明', 'age': 18}
In [1]: xiaoming = {"name": "小明", "age": 18, "height": 1.75}
In [2]: xiaoming.clear()
In [3]: print(xiaoming) # return {}
4)其它
函数 | 描述 |
---|---|
len(d) | 返回字典 d 中的项数。 |
list(d) | 返回字典 d 中使用的所有键的列表。 |
例如:
In [1]: xiaoming = {"name": "小明", "age": 18, "height": 1.75}
In [2]: print(len(xiaoming)) # return 3
In [3]: print(list(xiaoming)) # return ['name', 'age', 'height']
方法 | 描述 |
---|---|
dict.get(key[, default]) | 如果 key 存在于字典中则返回 key 的值,否则返回 default。 \newline 如果 default 未给出则默认为 None,因而此方法绝不会引发 KeyError。 |
dict.keys() | 返回由字典键组成的一个新视图。 |
dict.values() | 返回由字典值组成的一个新视图。 |
dict.items() | 返回由字典项 ((键, 值) 对) 组成的一个新视图。 |
例如:
In [1]: xiaoming = {"name": "小明", "age": 18, "height": 1.75}
In [2]: print(xiaoming.get('name')) # return 小明
In [3]: print(xiaoming.get('weight')) # return None
In [4]: print(xiaoming.keys()) # return dict_keys(['name', 'age', 'height'])
In [5]: print(xiaoming.values()) # return dict_values(['小明', 18, 1.75])
In [6]: print(xiaoming.items()) # return dict_items([('name', '小明'), ('age', 18), ('height', 1.75)])
注意:由 dict.keys(), dict.values() 和 dict.items() 所返回的对象是视图对象。 该对象提供字典条目的一个动态视图,这意味着当字典改变时,视图也会相应改变。
例如:
In [1]: xiaoming = {"name": "小明", "age": 18, "height": 1.75}
In [2]: keys = xiaoming.keys()
In [3]: print(list(keys)) # return ['name', 'age', 'height']
In [4]: del xiaoming['name']
In [5]: print(list(keys)) # return ['age', 'height']
2.3 遍历字典与嵌套
1)遍历字典
● 遍历所有的键值对:要编写用于遍历字典的 for 循环,可声明两个变量,用于存储键值对中的键和值。对于这两个变量,可使用任何名称。
In [1]: favorite_languages = {'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', }
In [2]: for name, language in favorite_languages.items():
In [3]: print(name.title() + "'s favorite language is " + language.title() + ".")
Out[3]: Jen's favorite language is Python.
Sarah's favorite language is C.
Edward's favorite language is Ruby.
Phil's favorite language is Python.
● 遍历字典中的所有键:
In [1]: favorite_languages = {'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', }
In [2]: for name in favorite_languages.keys():
In [3]: print(name.title())
Out[3]: Jen
Sarah
Edward
Phil
遍历字典时,会默认遍历所有的键,因此如果将上述代码中的 for name in favorite_languages.keys(): 替换为 for name in favorite_languages:,输出将不变。
● 按顺序遍历字典中的所有键:字典总是明确地记录键和值之间的关联关系,但获取字典的元素时,获取顺序是不可预测的。这不是问题,因为通常你想要的只是获取与键相关联的正确的值。 要以特定的顺序返回元素,一种办法是在 for 循环中对返回的键进行排序。为此可使用函数 sorted( ) 来获得按特定顺序排列的键列表的副本。
In [1]: favorite_languages = {'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', }
In [2]: for name in sorted(favorite_languages.keys()):
In [3]: print(name.title())
● 遍历字典中的所有值:
In [1]: favorite_languages = {'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', }
In [2]: print("The following languages have been mentioned:")
In [3]: for language in favorite_languages.values():
In [4]: print(language.title())
Out[4]: The following languages have been mentioned:
Python
C
Ruby
Python
这种做法提取字典中所有的值,而没有考虑是否重复。涉及的值很少时,这也许不是问题,但如果值很多,最终的列表可能包含大量的重复项。为剔除重复项,可使用集合(set)。集合类似于列表,但每个元素都必须是独一无二的:
In [1]: favorite_languages = {'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', }
In [2]: print("The following languages have been mentioned:")
In [3]: for language in set(favorite_languages.values()):
In [4]: print(language.title())
Out[4]: The following languages have been mentioned:
C
Ruby
Python
通过对包含重复元素的列表调用 set( ),可让Python找出列表中独一无二的元素,并使用这些元素来创建一个集合。
2)嵌套
有时候,需要将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套。你可以在列表中嵌套字典、在字典中嵌套列表甚至在字典中嵌套字典。正如下面的示例将演示的,嵌套是一项强大的功能。
● 在列表中存储字典:
# 创建一个用于存储外星人的空列表
aliens = []
# 创建30个绿色的外星人
for alien_number in range (0,30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
for alien in aliens[0:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
# 显示前五个外星人
for alien in aliens[0:5]:
print(alien)
print("...")
{'speed': 'medium', 'color': 'yellow', 'points': 10}
{'speed': 'medium', 'color': 'yellow', 'points': 10}
{'speed': 'medium', 'color': 'yellow', 'points': 10}
{'speed': 'slow', 'color': 'green', 'points': 5}
{'speed': 'slow', 'color': 'green', 'points': 5}
...
经常需要在列表中包含大量的字典,而其中每个字典都包含特定对象的众多信息。例如,你可能需要为网站的每个用户创建一个字典,并将这些字典存储在一个名为 users 的列表中。在这个列表中,所有字典的结构都相同,因此你可以遍历这个列表,并以相同的方式处理其中的每个字典。
● 在字典中存储列表:
favorite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}
for name, languages in favorite_languages.items():
print("\n" + name.title() + "'s favorite languages are:")
for language in languages:
print("\t" + language.title())
Jen's favorite languages are:
Python
Ruby
Sarah's favorite languages are:
C
Phil's favorite languages are:
Python
Haskell Edward's favorite languages are:
Ruby
Go
● 在字典中存储字典:
users = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}
for username, user_info in users.items():
print("\nUsername: " + username)
full_name = user_info['first'] + " " + user_info['last']
location = user_info['location']
print("\tFull name: " + full_name.title())
print("\tLocation: " + location.title())
Username: aeinstein
Full name: Albert Einstein
Location: Princeton
Username: mcurie
Full name: Marie Curie
Location: Paris