3.python元组

2022-10-16  本文已影响0人  生信百宝箱

3.元组

Python的元组与列表类似,不同之处在于元组的元素不能修改(前面多次提到的字符串也是不能修改的)。创建元组的方法很简单:如果你使用逗号分隔了一些值,就会自动创建元组。

3.1 tuple函数

在Python中,tuple()函数是针对元组操作的,功能是把传入的序列转换为元组并返回得到的元组,若传入的参数序列是元组,就会将传入参数原样返回。

#列表转元组
>>> test=["hi","python"]
>>> test1=tuple(test)
>>> test1
('hi', 'python')
#字符串转元组
>>> test2="hi,python"
>>> test3=tuple(test2)
>>> test3
('h', 'i', ',', 'p', 'y', 't', 'h', 'o', 'n')

在Python中,可以使用tuple()函数将列表转换为元组,也可以使用list()函数将元组转换为列表,即可以通过tuple()函数和list()函数实现元组和列表的相互转换。

3.2 元组操作

3.2.1 访问元组(与列表相同)

元组的访问是比较简单的,和列表的访问类似,直接通过索引下标即可访问元组中的值。

>>> test1
('hi', 'python', 'hi', 'world')
>>> test1[1]
'python'
>>> test1[1:3]
('python', 'hi')

3.2.2 修改元组

元组中的元素不允许修改,但是可以对元组进行连接组合。

元组连接组合的实质是生成了一个新的元组,并非是修改了原本的某一个元组。

>>> test1=("hi",)
>>> test2=("python",)
>>> test1+test2
('hi', 'python')

3.2.3 删除元组

元组中的元素是不允许删除的,但可以使用del语句删除整个元组。

>>> test1=("hi","python")
>>> del test1
>>> test1
Traceback (most recent call last):
  File "D:\py3.10\lib\code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
NameError: name 'test1' is not defined. Did you mean: 'test'?

可以删除元组,元组被删除后,若继续访问元组,程序会报错,报错信息告诉我们greeting没有定义,即前面定义的变量在这个时候已经不存在了。

3.2.4 元组的索引和截取

元组也是一个序列,可以通过索引下标访问元组中指定位置的元素,也可以使用分片的方式得到指定的元素。

元组通过分片的方式得到的序列结果也是元组。

>>> test1=("hi","python","hi","world")
>>> test1[1]
'python'
>>> test1[1:3]
('python', 'hi')

3.3 元组内置函数

在Python中,为元组提供了一些内置函数,如计算元素个数、返回最大值、返回最小值、列表转换等函数。

#内置函数使用
>>> test
(1, 2, 5, 8, 9)
>>> len(test)
5
>>> max(test)
9
>>> min(test)
1
#报错
>>> test=(1,2,5,8,9,"10")
>>> max(test)
Traceback (most recent call last):
  File "D:\py3.10\lib\code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
TypeError: '>' not supported between instances of 'str' and 'int'

max(tuple)、min(tuple)函数既可以应用于数值元组,也可以应用于字符串元组,但是不能应用于数值和字符串混合的元组中。

上一篇下一篇

猜你喜欢

热点阅读