Python 元组完全指南2

打印 上一主题 下一主题

主题 541|帖子 541|积分 1623

更新元组

更改元组的值

元组是不可更改的,但有一种变通方法。您可以将元组转换为列表,更改列表,然后将列表转换回元组。
示例:
  1. x = ("apple", "banana", "cherry")
  2. y = list(x)
  3. y[1] = "kiwi"
  4. x = tuple(y)
  5. print(x)
复制代码
添加项

由于元组是不可变的,没有内置的append()方法,但可以使用其他方法添加项。
转换为列表,添加项,再转换回元组:
  1. thistuple = ("apple", "banana", "cherry")
  2. y = list(thistuple)
  3. y.append("orange")
  4. thistuple = tuple(y)
复制代码
将元组添加到元组中:
  1. thistuple = ("apple", "banana", "cherry")
  2. y = ("orange",)
  3. thistuple += y
复制代码
删除项

元组不支持直接删除项,但可以转换为列表,删除项,再转换回元组。
  1. thistuple = ("apple", "banana", "cherry")
  2. y = list(thistuple)
  3. y.remove("apple")
  4. thistuple = tuple(y)
复制代码
或者可以完全删除元组:
  1. thistuple = ("apple", "banana", "cherry")
  2. del thistuple
复制代码
Python - 解包元组

解包元组

可以将元组的值提取回变量,称为解包。
示例:
  1. fruits = ("apple", "banana", "cherry")
  2. (green, yellow, red) = fruits
  3. print(green)
  4. print(yellow)
  5. print(red)
复制代码
使用星号 *

如果变量的数量少于值的数量,可以在变量名后添加星号*,将剩余的值收集到一个列表中。
示例:
  1. fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
  2. (green, yellow, *red) = fruits
  3. print(green)
  4. print(yellow)
  5. print(red)
复制代码
多重元组

可以使用*运算符将元组的内容复制多次。
示例:
  1. fruits = ("apple", "banana", "cherry")
  2. mytuple = fruits * 2
  3. print(mytuple)
复制代码
遍历元组

可以使用for循环或通过索引编号来遍历元组项。
示例:
  1. thistuple = ("apple", "banana", "cherry")
  2. for x in thistuple:
  3.   print(x)
复制代码
通过索引编号遍历:
  1. thistuple = ("apple", "banana", "cherry")
  2. for i in range(len(thistuple)):
  3.   print(thistuple[i])
复制代码
使用while循环遍历:
  1. thistuple = ("apple", "banana", "cherry")
  2. i = 0
  3. while i < len(thistuple):
  4.   print(thistuple[i])
  5.   i = i + 1
复制代码
合并元组

合并两个元组

可以使用+运算符合并两个元组。
示例:
  1. tuple1 = ("a", "b", "c")
  2. tuple2 = (1, 2, 3)
  3. tuple3 = tuple1 + tuple2
  4. print(tuple3)
复制代码
多重元组

可以使用*运算符将元组的内容复制多次。
示例:
  1. fruits = ("apple", "banana", "cherry")
  2. mytuple = fruits * 2
  3. print(mytuple)
复制代码
元组方法

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

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

为了方便其他设备和平台的小伙伴观看往期文章,链接奉上:
公众号搜索Let us Coding知乎开源中国CSDN思否掘金InfoQ简书博客园慕课51CTOhelloworld腾讯开发者社区阿里开发者社区
看完如果觉得有帮助,欢迎点赞、收藏关注

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

小秦哥

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表