本文介绍Python中最基础的数据结构,列表和元组。
- 通用序列操作
>>> Sunwukong = ['Sun wu kong', 500]
>>> Zhubajie = ['Zhu ba jie', 800]
>>>
>>> Qujingtuandui = [Sunwukong, Zhubajie]
>>>
>>> Qujingtuandui
[['Sun wu kong', 500], ['Zhu ba jie', 800]]
>>>
索引
>>> string = 'The meaning of life?'
>>> string[0]
'T'
>>> string[-1]
'?'
>>> string[-2]
'e'
>>> string[3:]
' meaning of life?'
>>> string[:-3]
'The meaning of li'
获取输入的地4位数据
>>> fourth = input('Year: ')[3]
Year: 2019
>>> fourth
'9'
>>>
不同的步长访问
>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>
>>> numbers[0:10:1]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> numbers[0:10:3]
[1, 4, 7, 10]
>>>
>>> numbers[0:10:2]
[1, 3, 5, 7, 9]
>>> numbers[0:10:5]
[1, 6]
>>>
相加
>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>> ['1', '2', '3'] + 'world!'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list
>>> ['1', '2', '3'] + ['world!']
['1', '2', '3', 'world!']
乘法
>>> 'python ' * 6
'python python python python python python '
>>>
>>> [100] * 5
[100, 100, 100, 100, 100]
- 列表:Python的主力
鉴于不能像修改列表那样修改字符串,因此在有些情况下使用字符串来创建列表很有帮助。
为此,可使用函数 list
>>> list('Hello')
['H', 'e', 'l', 'l', 'o']
请注意,可将任何序列(而不仅仅是字符串)作为 list 的参数。
修改列表元素值
>>> x = [3, 6, 9]
>>> x[1] = 200
>>> x
[3, 200, 9]
删除元素
>>> x = [3, 200, 9]
>>> del x[2]
>>> x
[3, 200]
给切片赋值
>>> name = list('Perl')
>>> name
['P', 'e', 'r', 'l']
>>> name[2:] = list('ar')
>>> name
['P', 'e', 'a', 'r']
列表方法
列表增加一个元素
>>> lst = [1, 2, 3]
>>> lst.append(4)
>>> lst
[1, 2, 3, 4]
清空列表
>>> lst.clear()
>>> lst
[]
统计元素数量
>>> x = [[3,3], 3, 3, [1, 2, 3]]
>>> x.count(3)
2
>>> x.count([3,3])
1
扩展列表
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a.extend(b)
>>> a
[1, 2, 3, 4, 5, 6]
获取列表元素的位置
>>> knights = ['We', 'are', 'the', 'knights', 'who', 'say', 'ni']
>>> knights.index('who')
4
插入元素
>>> numbers = [1, 2, 3, 5, 6, 7]
>>> numbers.insert(3, 'four')
>>> numbers
[1, 2, 3, 'four', 5, 6, 7]
列表末尾元素弹出
>>> x = [1, 2, 3]
>>> x.pop()
3
>>> x
[1, 2]
## 注意 pop 是唯一既修改列表又返回一个非 None 值的列表方法。
移除任意元素
>>> x = ['to', 'be', 'or', 'not', 'to', 'be']
>>> x.remove('be')
>>> x
['to', 'or', 'not', 'to', 'be']
倒序
>>> x = [1, 2, 3]
>>> x.reverse()
>>> x
[3, 2, 1]
排序
>>> x = [4, 6, 2, 1, 7, 9]
>>> x.sort()
>>> x
[1, 2, 4, 6, 7, 9]
高级排序
>>> x = ['aardvark', 'abalone', 'acme', 'add', 'aerate']
>>> x.sort(key=len)
>>> x
['add', 'acme', 'aerate', 'abalone', 'aardvark']
元组(不可修改的序列)
>>> 3 * (40 + 2)
126
>>> 3 * (40 + 2,)
(42, 42, 42)
>>> tuple([1, 2, 3])
(1, 2, 3)
>>> tuple('abc')
('a', 'b', 'c')
>>> tuple((1, 2, 3))
(1, 2, 3)
元组并不太复杂,而且除创建和访问其元素外,可对元组执行的操作不多。元组的创建及其元素的访问方式与其他序列相同。
列表元组完。