1. 数值相加
当两侧操作数都是数值(整数或浮点数)时,加号运算符执行算术加法操作。
result = 3 + 5 # 结果是8
result += 5 # 即使 result = result+5
2. 字符串连接
greeting = "Hello, " + "world!" # 结果是"Hello, world!"
3. 列表合并
当两侧操作数都是列表时,列表合并成一个新的列表。
combined_list = [1, 2, 3] + [4, 5, 6] # 结果是[1, 2, 3, 4, 5, 6]
4. 元组合并
类似于列表合并。
combined_tuple = (1, 2, 3) + (4, 5, 6) # 结果是(1, 2, 3, 4, 5, 6)
注意,虽然加号运算符非常灵活,但它不支持类型之间的隐式转换,即它要求两侧的操作数类型必须兼容。
5 Python 内置函数 enumerate()
用于遍历可迭代对象(如列表、元组、字符串等)时同时获取元素的索引和值。它返回一个 迭代器,每次迭代返回一个包含两个元素的元组,第一个是元素的索引,第二个是元素的值。
enumerate(iterable, start=0)
iterable:这是一个可以被迭代的对象(如列表、元组、字符串等)。
start:这是可选参数,表示索引的起始值,默认从 0 开始。
返回值:
enumerate() 返回的是一个可迭代的对象,它会生成一个包含索引和值的元组。你可以使用 for 循环来遍历这些元组。
my_list = ['a', 'b', 'c', 'd']
# 迭代取全部元素
for index, value in enumerate(my_list):
print(f"Index: {index}, Value: {value}")
# 指定集合开始下标
for index, value in enumerate(my_list, start=2):
print(f"Index: {index}, Value: {value}")
#将 enumerate 用于列表推导式
indexed_list = [(index, value) for index, value in enumerate(my_list)]
print(indexed_list)
l1 = ['a', 'b', 'c', 'd']
l2 = ['G', 'H']
for index, value in enumerate(l1+l2):
print(f"Index: {index}, Value: {value}")
# 遍历多维数组
nested_list = [['apple', 'banana'], ['cherry', 'date'], ['fig', 'grape']]
for outer_index, inner_list in enumerate(nested_list):
for inner_index, fruit in enumerate(inner_list):
print(f"Outer Index: {outer_index}, Inner Index: {inner_index}, Fruit: {fruit}")
# 根据索引过滤
numbers = [1, 2, 3, 4, 5, 6]
filtered_numbers = [number for index, number in enumerate(numbers) if index % 2 == 0]
print(filtered_numbers)
# 输出:
# [2, 4, 6]
# 遍历字典并同时获取键和值
my_dict = {'a': 1, 'b': 2, 'c': 3}
for index, (key, value) in enumerate(my_dict.items()):
print(f"Index: {index}, Key: {key}, Value: {value}")