元组与列表都可归为序列类型,与列表有许多相同的用法。需要注意的是元组是不可变的序列类型,生成后是固定的,不能对其元素进行替换或删除。
以下内容为python中元组部分知识和操作(含有代码示例),内容可查看目录。
相关文章
目录
# 元组的定义赋值
kong = tuple()
print('创建一个元组:', kong)
food1 = ('rice', 'bread')
print('元组的定义赋值:', food1)
food2 = 'apple', 'pear'
print('也可不用圆括号:', food2)
输出结果如下:
创建一个元组: ()
元组的定义赋值: ('rice', 'bread')
也可不用圆括号: ('apple', 'pear')
# 多级索引
food = ('rice', 'bread', ('apple', 'pear'))
print('多级索引:', food[-1][0])
输出结果如下:
多级索引: apple
# 多变量同步赋值
a, b = 'apple', 'pear' # 也可以加上圆括号
print('多变量同步赋值:', a, '---', b)
输出结果如下:
多变量同步赋值: apple --- pear
# 循环遍历
eat = (('小明', 'apple'), ('小红', 'pear'))
for i, j in eat:
print('循环遍历:', i, '在吃', j)
输出结果如下:
循环遍历: 小明 在吃 apple
循环遍历: 小红 在吃 pear
# 函数多返回值
def hanshu(n):
a = n
b = n ** 2
c = n ** 3
return a, b, c
num = hanshu(3)
print('函数多返回值:', num)
输出结果如下:
函数多返回值: (3, 9, 27)
# 元组与列表的转换
number1 = (1, 3, 5, 7, 9)
print('元组转列表:', list(number1))
number2 = [1, 3, 5, 7, 9]
print('列表转元组:', tuple(number2))
输出结果如下:
元组转列表: [1, 3, 5, 7, 9]
列表转元组: (1, 3, 5, 7, 9)
# zip()函数
# 用于将可迭代的对象(如元组、列表)作为参数,将对象中的元素相对应的打包成元组。
eat1 = ('小明', 'apple')
eat2 = ('小红', 'pear')
eat3 = ('李华', '英语作文')
dabao = zip(eat1, eat2, eat3)
for i in dabao:
print('zip()函数:', i)
输出结果如下:
zip()函数: ('小明', '小红', '李华')
zip()函数: ('apple', 'pear', '英语作文')