前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python 元组完全指南2

Python 元组完全指南2

原创
作者头像
小万哥
发布2023-10-07 21:18:15
1370
发布2023-10-07 21:18:15
举报
文章被收录于专栏:程序人生丶程序人生丶

更新元组

更改元组的值

元组是不可更改的,但有一种变通方法。您可以将元组转换为列表,更改列表,然后将列表转换回元组。

示例:

代码语言:Markdown
复制
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)

添加项

由于元组是不可变的,没有内置的append()方法,但可以使用其他方法添加项。

转换为列表,添加项,再转换回元组:

代码语言:Python
复制
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)

将元组添加到元组中:

代码语言:Python
复制
thistuple = ("apple", "banana", "cherry")
y = ("orange",)
thistuple += y

删除项

元组不支持直接删除项,但可以转换为列表,删除项,再转换回元组。

代码语言:Python
复制
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)

或者可以完全删除元组:

代码语言:Python
复制
thistuple = ("apple", "banana", "cherry")
del thistuple

Python - 解包元组

解包元组

可以将元组的值提取回变量,称为解包。

示例:

代码语言:Python
复制
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)

使用星号 *

如果变量的数量少于值的数量,可以在变量名后添加星号*,将剩余的值收集到一个列表中。

示例:

代码语言:Python
复制
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red)

多重元组

可以使用*运算符将元组的内容复制多次。

示例:

代码语言:Python
复制
fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
print(mytuple)

遍历元组

可以使用for循环或通过索引编号来遍历元组项。

示例:

代码语言:Python
复制
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
  print(x)

通过索引编号遍历:

代码语言:Python
复制
thistuple = ("apple", "banana", "cherry")
for i in range(len(thistuple)):
  print(thistuple[i])

使用while循环遍历:

代码语言:Python
复制
thistuple = ("apple", "banana", "cherry")
i = 0
while i < len(thistuple):
  print(thistuple[i])
  i = i + 1

合并元组

合并两个元组

可以使用+运算符合并两个元组。

示例:

代码语言:Python
复制
tuple1 = ("a", "b", "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)

多重元组

可以使用*运算符将元组的内容复制多次。

示例:

代码语言:Python
复制
fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
print(mytuple)

元组方法

Python 提供了两个内置方法,可以在元组上使用:

  • count(): 返回指定值在元组中出现的次数。
  • index(): 搜索元组中指定的值,并返回其找到的位置。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 更新元组
    • 更改元组的值
      • 添加项
        • 删除项
        • Python - 解包元组
          • 解包元组
            • 使用星号 *
              • 多重元组
              • 遍历元组
              • 合并元组
                • 合并两个元组
                  • 多重元组
                  • 元组方法
                  领券
                  问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
                  http://www.vxiaotou.com