您的位置: 网站首页> python基础> 当前文章

元组定义,元素获取,元素*重复,元祖相加等操作

老董-我爱我家房产SEO2020-09-14169围观,130赞

  定义:

  Python的元组与列表类似,不同之处在于元组的元素不能修改。元组使用小括号,列表使用方括号。

  一:元组创建:

# ‐*‐ coding: utf‐8 ‐*‐

# 创建空元组
print('以下是空元组')
t1 = tuple()
t2 = ()
print(t1,t2)

# 创建自定义元组
print('以下是自定义元组')
t3 = tuple(range(3)) # range是个函数,后面讲解
t4 = (1, 2, 3, )
t5 = tuple([1,2,3])
t6 = ('a', 'b', 'c')
t7 = tuple('1234abc')
t8 = (1, 2, 3, 'a', 'b', [4, 5], 99.9, (3, 5))

t9 = 1,2,4,5 # 这个也是元组,可以不用写括号,默认会添加

t10 = (2,) # 单元素元素问题, 一定要加逗号
print(t3,t4,t5,t6,t7,t8,t9,t10)
D:installpython3python.exe D:/pyscript/python3_script/test66.py
以下是空元组
() ()
以下是自定义元组
(0, 1, 2) (1, 2, 3) (1, 2, 3) ('a', 'b', 'c') ('1', '2', '3', '4', 'a', 'b', 'c') (1, 2, 3, 'a', 'b', [4, 5], 99.9, (3, 5)) (1, 2, 4, 5) (2,)

Process finished with exit code 0

 

  二:元组相关操作:

  1. 获取元组中的元素

      通过下标获取

      通过切片获取

      通过for循环来遍历元组

  2. 元组的内置函数count,index

     index和count与字符串和列表中的用法相同

  3. 两个元组相加

  4. 元组重复

# ‐*‐ coding: utf‐8 ‐*‐

print('以下是获取元组元素')
t1 = (1,2,3,4,5)
print(t1)
# 通过下标获取
print(t1[0])
# 通过切片获取
print(t1[0:2])
# 通过for循环来遍历元组
for t in t1:
    print(t)

print('以下是index count用法')
t = tuple('abcde')
# index返回元素在元组中的位置,如果不存在则会抛出ValueError异常
print(t.index('a'))
# count统计元素在元组中出现的次数,如果不存在,则为0
print(t.count('a'))

print('以下是元素相加和重复')
t1 = tuple("abcde")
t2 = (0,1,2,3,4)
# 通过加号(+)可以将两个元组中的元素合并在一起,形成一个新的元组
t3 = t1 + t2
print(t3)

t1 = tuple("abcde")
# 星号(*)可以将元组中的元素重复N次,形成一个新的元组
t2 = t1 * 3
print(t2)
D:installpython3python.exe D:/pyscript/python3_script/test66.py
以下是获取元组元素
(1, 2, 3, 4, 5)
1
(1, 2)
1
2
3
4
5
以下是index count用法
0
1
以下是元素相加和重复
('a', 'b', 'c', 'd', 'e', 0, 1, 2, 3, 4)
('a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e')

Process finished with exit code 0


  5. 里面的元素不可修改

# ‐*‐ coding: utf‐8 ‐*‐

t1 = (1,2,3,4,5)
# 以下是错误的 报错 TypeError: 'tuple' object does not support item assignment
t1[0] = 2

# 重新定义变量
t1 = ('a','b','c')
D:installpython3python.exe D:/pyscript/python3_script/test66.py
Traceback (most recent call last):
  File "D:/pyscript/python3_script/test66.py", line 5, in 
    t1[0] = 2
TypeError: 'tuple' object does not support item assignment

Process finished with exit code 1

 

很赞哦!

python编程网提示:转载请注明来源www.python66.com。
有宝贵意见可添加站长微信(底部),获取技术资料请到公众号(底部)。同行交流请加群 python学习会

文章评论

    元组定义,元素获取,元素*重复,元祖相加等操作文章写得不错,值得赞赏

站点信息

  • 网站程序:Laravel
  • 客服微信:a772483200