4. Python的序列

本文详细介绍了Python中的序列类型,包括列表、元组、集合和字典。列表是可变的,元组是不可变的,两者都支持基本操作如访问元素、切片、加法和乘法。序列的共有操作包括成员运算符、求长度、最大值和最小值。集合是无序的,不包含重复元素,支持并、交和差集操作。字典是无序的键值对集合,键不可变,支持成员判断符和特殊操作。
摘要由CSDN通过智能技术生成

字符串str、列表list、元组tuple都是序列。序列有序的,且具有类似的基本操作。

字符串str、元组tuple是不可变类型,而列表list是可变类型。


列表list

列表通过[]定义,[]中是单个的元素,当[]中只含None元素时称为空列表。列表中的元素是可以任意改变的。

>>> type([1, 2, 3, 4, 5])
<class 'list'>

>>> type([])
<class 'list'>

对于一个列表,其内部元素的类型并不是固定的单一类型,可以是任意的类型。

>>> type(["hello world", 1, False])
<class 'list'>

列表内部的元素还可以是列表、元组、集合及字典。列表中元素为列表的列表称为嵌套列表。

>>> type([[1, "two", 'three'], ('zhang', 25, 'liu'), {30, 'wang', 'male'}, {'Bob': 85, 'Jack': 63, 'Ailce': 96}])
<class 'list'>
列表的基本操作
  • 访问列表元素:
>>> Jiaoyue = ["新月打击", "苍白之瀑", "月之降临", "月神冲刺"]

>>> Jiaoyue[0]
'新月打击'

>>> Jiaoyue[3]
'月神冲刺'

单个数字序号取到的是字符串,而不是列表。

  • 切片:
>>> Jiaoyue[0:2]
['新月打击', '苍白之瀑']

>>> Jiaoyue[-1]
'月神冲刺'

>>> Jiaoyue[-1:]
['月神冲刺']

>>> Jiaoyue[0:3:2]
['新月打击', '月之降临']

>>> Jiaoyue[:]
['新月打击', '苍白之瀑', '月之降临', '月神冲刺']

通过对列表进行切片得到的仍然是列表,而不是字符串。切片时第三个参数是步长,不指定默认为1。[:]表示进行复制,不影响原列表。

  • 相加:
>>> DF = ["闪现", "点燃", "月神冲刺"]

>>> Jiaoyue + DF
['新月打击', '苍白之瀑', '月之降临', '月神冲刺', '闪现', '点燃', '月神冲刺']

>>> Jiaoyue - DF
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    Jiaoyue - DF
TypeError: unsupported operand type(s) for -: 'list' and 'list'

两个列表相加得到的仍然是列表,且相同元素不会被去除。列表不支持减法操作。

  • 相乘:
>>> Jiaoyue * DF
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    Jiaoyue * DF
TypeError: can't multiply sequence by non-int of type 'list'

>>> DF * 3
['闪现', '点燃', '月神冲刺', '闪现', '点燃', '月神冲刺', '闪现', '点燃', '月神冲刺']

与字符串类似,列表之间不能相乘,列表只能与数字相乘,得到的仍然是列表,列表元素会重复对应数字的次数。


元组tuple

元组通过()定义,()中是单个的元素,当()中只含None元素时称为空元组。与列表不同,元组中的元素是不可改变的,元组可看作不可变的列表。

>>> type((1, 2, 3, 4, 5))
<class 'tuple'>

>>> type(())
<class 'tuple'>

对于一个元组,其内部元素的类型并不是固定的单一类型,可以是任意的类型。

>>> type((1, 'aaa', True))
<class 'tuple'>

元组内部的元素还可以是列表、元组、集合及字典。元组中元素为元组的元组称为嵌套元组。

>>> type(([1, "two", 'three'], ('zhang', 25, 'liu'), {30, 'wang', 'male'}, {'Bob': 85, 'Jack': 63, 'Ailce': 96}))
<class 'tuple'>

对于只含单个元素的元组,定义元组时需要注意一个小问题。

>>> t1 = (1)

>>> type(t1)
<class 'int'>

>>> t1
1

>>> type(('hello'))
<class 'str'>
>>> t2 = (1,)

>>> type(t2)
<class 'tuple'>

>>> t2
(1,)

只含单个元素的元组在定义时不要忘记添加,,否则不会作为tuple类型。列表不存在这个问题。

这是因为Python也使用()作为数学运算的优先级符号,这与元组的定义产生了冲突,所以Python规定只含单个元素的元组在定义时需要加上,

元组的基本操作
  • 访问元组元素:
>>> T = ('Zhangsan', 18, "male", 67)

>>> T[1]
18

>>> T[-2]
'male'

单个数字序号取到的是字符串,而不是元组。

  • 切片:
>>> T[0:2]
('Zhangsan', 18)

>>> T[-2:]
('male', 67)

>>> T[0:3:3]
('Zhangsan',)

>>> T[:]
('Zhangsan', 18, 'male', 67)

通过对元组进行切片得到的仍然是元组,而不是字符串。切片时第三个参数是步长,不指定默认为1。[:]表示进行复制,不影响原元组。

  • 相加:
>>> t = (17, 18, 19)

>>> T + t
('Zhangsan', 18, 'male', 67, 17, 18, 19)

>>> T - t
Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module>
    T - t
TypeError: unsupported operand type(s) for -: 'tuple' and 'tuple'

两个元组相加得到的仍然是元组,且相同元素不会被去除。元组不支持减法操作。

  • 相乘:
>>> T * t
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    T * t
TypeError: can't multiply sequence by non-int of type 'tuple'

>>> t * 3
(17, 18, 19, 17, 18, 19, 17, 18, 19)

与列表类似,元组之间不能相乘,元组只能与数字相乘,得到的仍然是元组,元组元素会重复对应数字的次数。


序列的共有操作

字符串、列表、元组都是序列,序列是有序的,通过上面我们可以看到序列的一些操作。接下来继续谈谈序列的共有操作。

  • 成员运算符innot in

用于判断一个元素是否在序列中。

>>> 3 in [1, 2, 3, 4, 5]
True

>>> 3 not in (6, 7, 8, 9, 10)
True

>>> 'hello' not in 'hello world'
False
  • len()方法:

求序列长度。

>>> len('hello world')
11

>>> len(['新月打击', '苍白之瀑', '月之降临', '月神冲刺', 1, 2, 3, 4, 5])
9

>>> len(('Zhangsan', 18, "male", 67))
4
  • max()min()方法:

求序列最大值及最小值。

>>> max('hello world')
'w'

>>> max(['新月打击', '苍白之瀑', '月之降临', '月神冲刺'])
'苍白之瀑'

>>> max(('Zhangsan', 18, "male", 67))
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    max(('Zhangsan', 18, "male", 67))
TypeError: '>' not supported between instances of 'int' and 'str'
>>> min('hello world')
' '

>>> min('helloworld')
'd'

>>> min(['新月打击', '苍白之瀑', '月之降临', '月神冲刺'])
'新月打击'

>>> min(('Zhangsan', 18, "male", 67))
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    min(('Zhangsan', 18, "male", 67))
TypeError: '<' not supported between instances of 'int' and 'str'

可以看到,max()min()不能对不同的元素类型进行比较,元素类型相同时可比较取得最大值及最小值。


集合set

不同于上面所讲的列表和元祖,它们都是序列。而集合是无序的,集合不是序列。

集合通过{}定义,{}中是单个的元素。集合中的元素是可改变的。

>>> type({1, 2, 3, 4, 5})
<class 'set'>

对于一个集合,其内部元素的类型并不是固定的单一类型,可以是任意类型。

>>> type({'abc', 222, False})
<class 'set'>

集合内部的元素还可以是元组,但不能是列表、集合及字典。

>>> type({('hello', 22)})
<class 'set'>

>>> type({['hello', 22]})
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    type({['hello', 22]})
TypeError: unhashable type: 'list'

>>> type({{'hello', 22}})
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    type({{'hello', 22}})
TypeError: unhashable type: 'set'

>>> type({{'hello':22, 'world': 23}})
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    type({{'hello':22, 'world': 23}})
TypeError: unhashable type: 'dict'

集合不支持通过序号访问其内部元素,当然也就无法切片。

>>> S = {'hello', 22, 'Bob', 'Student'}

>>> S[2]
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    S[2]
TypeError: 'set' object is not subscriptable

>>> S[0:2]
Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    S[0:2]
TypeError: 'set' object is not subscriptable

集合中元素不重复,集合中不会存在相同的元素。

>>> S1 = {1, 2, 3, 4, 1, 2, 3 ,4}

>>> S1
{1, 2, 3, 4}

集合支持前面所讲的len()max()min()等方法,也支持innot in这样的成员判断符。

>>> len(S1)
4

>>> max(S1)
4

>>> min(S1)
1

>>> 3 in S1
True

>>> 1 not in S1
False

还有个小问题,如何定义一个空的集合?

>>> type({})
<class 'dict'>

>>> type(set())
<class 'set'>

>>> len(set())
0

{}中只含None元素时,Python默认识别为字典dict类型。不过与列表、元组及字典类似,可以通过set()方法来定义一个空的集合。

集合的特殊操作
  • 求两集合差集-
>>> {1, 2, 3, 4, 5, 6} - {3, 4}
{1, 2, 5, 6}
  • 求两集合交集&
>>> {1, 2, 3, 4, 5, 6} & {3, 4}
{3, 4}
  • 求两集合并集|
>>> {1, 2, 3, 4, 5, 6} | {3, 4, 7}
{1, 2, 3, 4, 5, 6, 7}

字典dict

与集合一样,字典也不是序列,它是无序的。

字典也是通过{}定义,只不过{}中的元素是键-值对(k-v)。字典中元素的key是不可变的,而value是可以改变的。

为什么叫字典,因为它是根据其内部元素的key来查找对应的value。

>>> type({'name': 'Bob', 'age': 16, 'gender': 'male'})
<class 'dict'>

对于一个字典,其内部元素的类型并不是固定的单一类型,key可以是任意不可变类型,而value不可以是bool类型。

>>> type({0: Flase, True: 'True', 'age': 16})
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    type({0: Flase, True: 'True', 'age': 16})
NameError: name 'Flase' is not defined

>>> type({0: 'Flase', True: 'True', 'age': 16})
<class 'dict'>

和集合一样,字典内部元素的key可以是元组,但不能是列表、集合及字典,而value可以是列表、元组、集合及字典。

>>> type({['hello', 22]: 'Bob'})
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    type({['hello', 22]: 'Bob'})
TypeError: unhashable type: 'list'

>>> type({'Bob': ['hello', 22]})
<class 'dict'>

>>> type({('hello', 22): 'Bob'})
<class 'dict'>

>>> type({'Bob': ('hello', 22)})
<class 'dict'>

>>> type({{'hello', 22}: 'Bob'})
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    type({{'hello', 22}: 'Bob'})
TypeError: unhashable type: 'set'

>>> type({'Bob': {'hello', 22}})
<class 'dict'>

>>> type({{'hello': 22}: 'Bob'})
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    type({{'hello': 22}: 'Bob'})
TypeError: unhashable type: 'dict'

>>> type({'Bob': {'hello': 22}})
<class 'dict'>

集合不支持通过序号访问其内部元素,当然也就无法切片。

>>> {'name': 'Bob', 'age': 16, 'gender': 'male', 'job': 'student'}[2]
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    {'name': 'Bob', 'age': 16, 'gender': 'male', 'job': 'student'}[2]
KeyError: 2

>>> {'name': 'Bob', 'age': 16, 'gender': 'male', 'job': 'student'}[0:3]
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    {'name': 'Bob', 'age': 16, 'gender': 'male', 'job': 'student'}[0:3]
TypeError: unhashable type: 'slice'

字典中元素不重复,且key值不允许相同,value值无限制。

>>> {'name': 'Bob', 'age': 16, 'gender': 'male', 'job': 'student', 'name': 'Jack', 'age': 16}
{'name': 'Jack', 'age': 16, 'gender': 'male', 'job': 'student'}

字典也支持前面所讲的len()max()min()等方法,也支持innot in这样的成员判断符。

>>> len({'Q': '新月打击', 'W': '苍白之瀑', 'E': '月之降临', 'R': '月神冲刺'})
4

>>> max({'Q': '新月打击', 'W': '苍白之瀑', 'E': '月之降临', 'R': '月神冲刺'})
'W'

>>> min({'Q': '新月打击', 'W': '苍白之瀑', 'E': '月之降临', 'R': '月神冲刺'})
'E'

>>> 'W' in {'Q': '新月打击', 'W': '苍白之瀑', 'E': '月之降临', 'R': '月神冲刺'}
True

>>> '苍白之瀑'  not in {'Q': '新月打击', 'W': '苍白之瀑', 'E': '月之降临', 'R': '月神冲刺'}
True
字典的特殊操作
  • 访问字典元素:
>>> {'Q': '新月打击', 'W': '苍白之瀑', 'E': '月之降临', 'R': '月神冲刺'}['Q']
'新月打击'

>>> {'Q': '新月打击', 'W': '苍白之瀑', 'E': '月之降临', 'R': '月神冲刺'}['R']
'月神冲刺'

>>> {'Q': '新月打击', 'W': '苍白之瀑', 'E': '月之降临', 'R': '月神冲刺'}['E', 'R']
Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    {'Q': '新月打击', 'W': '苍白之瀑', 'E': '月之降临', 'R': '月神冲刺'}['E', 'R']
KeyError: ('E', 'R')

>>> {'Q': '新月打击', 'W': '苍白之瀑', 'E': '月之降临', 'R': '月神冲刺'}['E']['Q']
Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    {'Q': '新月打击', 'W': '苍白之瀑', 'E': '月之降临', 'R': '月神冲刺'}['E']['Q']
TypeError: string indices must be integers

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值