一、列表(List)
1. 定义与基本特性
列表是 Python 中最常用的数据结构之一,它是一个有序、可变的元素集合。列表使用方括号 []
来表示,元素之间用逗号分隔。
收起
python
# 示例列表
my_list = [1, 2, 3, 'apple', 'banana']
2. 访问列表元素
列表中的元素可以通过索引来访问,索引从 0 开始。也可以使用负数索引从列表末尾开始访问。
收起
python
# 访问第一个元素
first_element = my_list[0]
print(first_element) # 输出: 1# 访问最后一个元素
last_element = my_list[-1]
print(last_element) # 输出: 'banana'
3. 切片操作
切片用于获取列表的子集,语法为 list[start:stop:step]
。
收起
python
# 获取索引 1 到 3 的元素(不包括索引 3)
sliced_list = my_list[1:3]
print(sliced_list) # 输出: [2, 3]# 每隔一个元素取一个
stepped_list = my_list[::2]
print(stepped_list) # 输出: [1, 3, 'banana']
4. 修改列表元素
由于列表是可变的,可以直接通过索引修改元素的值。
收起
python
# 修改第二个元素
my_list[1] = 20
print(my_list) # 输出: [1, 20, 3, 'apple', 'banana']
5. 列表常用方法
- append():在列表末尾添加一个元素。
收起
python
my_list.append('cherry')
print(my_list) # 输出: [1, 20, 3, 'apple', 'banana', 'cherry']
- extend():将一个可迭代对象的元素添加到列表末尾。
收起
python
new_list = [4, 5]
my_list.extend(new_list)
print(my_list) # 输出: [1, 20, 3, 'apple', 'banana', 'cherry', 4, 5]
- insert():在指定索引位置插入一个元素。
收起
python
my_list.insert(2, 'orange')
print(my_list) # 输出: [1, 20, 'orange', 3, 'apple', 'banana', 'cherry', 4, 5]
- remove():移除列表中第一个匹配的元素。
收起
python
my_list.remove('apple')
print(my_list) # 输出: [1, 20, 'orange', 3, 'banana', 'cherry', 4, 5]
- pop():移除并返回指定索引位置的元素,默认移除最后一个元素。
收起
python
popped_element = my_list.pop(2)
print(popped_element) # 输出: 'orange'
print(my_list) # 输出: [1, 20, 3, 'banana', 'cherry', 4, 5]
- sort():对列表进行排序。
收起
python
num_list = [3, 1, 2]
num_list.sort()
print(num_list) # 输出: [1, 2, 3]
- reverse():反转列表元素的顺序。
收起
python
num_list.reverse()
print(num_list) # 输出: [3, 2, 1]
6. 列表的遍历
可以使用 for
循环遍历列表中的元素。
收起
python
for element in my_list:print(element)
二、字符串(String)
1. 定义与基本特性
字符串是由零个或多个字符组成的不可变序列,可以使用单引号 '
、双引号 "
或三引号 '''
或 """
来表示。
收起
python
# 示例字符串
my_string = 'Hello, World!'
2. 访问字符串字符
字符串中的字符可以通过索引访问,索引规则与列表相同。
收起
python
# 访问第一个字符
first_char = my_string[0]
print(first_char) # 输出: 'H'# 访问最后一个字符
last_char = my_string[-1]
print(last_char) # 输出: '!'
3. 切片操作
字符串也支持切片操作,用法与列表类似。
收起
python
# 获取索引 0 到 5 的子字符串(不包括索引 5)
sub_string = my_string[0:5]
print(sub_string) # 输出: 'Hello'
4. 字符串常用方法
- upper():将字符串中的所有字母转换为大写。
收起
python
upper_string = my_string.upper()
print(upper_string) # 输出: 'HELLO, WORLD!'
- lower():将字符串中的所有字母转换为小写。
收起
python
lower_string = my_string.lower()
print(lower_string) # 输出: 'hello, world!'
- strip():去除字符串两端的空白字符。
收起
python
whitespace_string = ' Hello, World! '
stripped_string = whitespace_string.strip()
print(stripped_string) # 输出: 'Hello, World!'
- replace():替换字符串中的指定子字符串。
收起
python
replaced_string = my_string.replace('World', 'Python')
print(replaced_string) # 输出: 'Hello, Python!'
- split():将字符串按指定分隔符分割成列表。
收起
python
split_list = my_string.split(',')
print(split_list) # 输出: ['Hello', ' World!']
- join():将可迭代对象中的元素用指定字符串连接成一个新的字符串。
收起
python
new_string = '-'.join(['apple', 'banana', 'cherry'])
print(new_string) # 输出: 'apple-banana-cherry'
5. 字符串的遍历
可以使用 for
循环遍历字符串中的每个字符。
收起
python
for char in my_string:print(char)
6. 字符串格式化
- 旧式格式化:使用
%
操作符。
收起
python
name = 'John'
age = 25
old_format = 'My name is %s and I am %d years old.' % (name, age)
print(old_format) # 输出: 'My name is John and I am 25 years old.'
- 新式格式化:使用
format()
方法。
收起
python
new_format = 'My name is {} and I am {} years old.'.format(name, age)
print(new_format) # 输出: 'My name is John and I am 25 years old.'
- f - 字符串:Python 3.6 及以上版本支持,使用
f
前缀。
收起
python
f_string = f'My name is {name} and I am {age} years old.'
print(f_string) # 输出: 'My name is John and I am 25 years old.'
三、字典(Dictionary)
1. 定义与基本特性
字典是一种无序、可变的数据结构,用于存储键值对。字典使用花括号 {}
来表示,键和值之间用冒号 :
分隔,键值对之间用逗号分隔。
收起
python
# 示例字典
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
2. 访问字典元素
可以通过键来访问字典中的值。
收起
python
# 访问 'name' 对应的值
name = my_dict['name']
print(name) # 输出: 'John'# 使用 get() 方法访问,避免键不存在时的错误
age = my_dict.get('age')
print(age) # 输出: 25# 键不存在时返回默认值
country = my_dict.get('country', 'Unknown')
print(country) # 输出: 'Unknown'
3. 修改和添加字典元素
可以通过键来修改或添加字典中的元素。
收起
python
# 修改 'age' 的值
my_dict['age'] = 26
print(my_dict) # 输出: {'name': 'John', 'age': 26, 'city': 'New York'}# 添加新的键值对
my_dict['country'] = 'USA'
print(my_dict) # 输出: {'name': 'John', 'age': 26, 'city': 'New York', 'country': 'USA'}
4. 删除字典元素
可以使用 del
语句或 pop()
方法删除字典中的元素。
收起
python
# 使用 del 语句删除 'city' 键值对
del my_dict['city']
print(my_dict) # 输出: {'name': 'John', 'age': 26, 'country': 'USA'}# 使用 pop() 方法删除 'age' 键值对并返回其值
age = my_dict.pop('age')
print(age) # 输出: 26
print(my_dict) # 输出: {'name': 'John', 'country': 'USA'}
5. 字典常用方法
- keys():返回字典中所有键的视图。
收起
python
keys = my_dict.keys()
print(keys) # 输出: dict_keys(['name', 'country'])
- values():返回字典中所有值的视图。
收起
python
values = my_dict.values()
print(values) # 输出: dict_values(['John', 'USA'])
- items():返回字典中所有键值对的视图。
收起
python
items = my_dict.items()
print(items) # 输出: dict_items([('name', 'John'), ('country', 'USA')])
- update():将一个字典的键值对更新到另一个字典中。
收起
python
new_dict = {'city': 'New York', 'age': 25}
my_dict.update(new_dict)
print(my_dict) # 输出: {'name': 'John', 'country': 'USA', 'city': 'New York', 'age': 25}
6. 字典的遍历
可以使用 for
循环遍历字典的键、值或键值对。
收起
python
# 遍历键
for key in my_dict.keys():print(key)# 遍历值
for value in my_dict.values():print(value)# 遍历键值对
for key, value in my_dict.items():print(key, value)