python3基础语法工具书(2)

2019-03-14  本文已影响0人  张小张x86

列表

列表属于序列

函数list

鉴于不能像修改列表那样修改字符串,因此在有些情况下使用字符串来创建列表很有帮助。 为此,可使用函数list。

>>> list('Hello')
['H', 'e', 'l', 'l', 'o']

列表基本操作

>>> x = [1, 1, 1] 
>>> x[1] = 2
>>> x
[1, 2, 1]
>>> names = ['Alice', 'Beth', 'Cecil', 'Dee-Dee', 'Earl']
>>> del names[2]
>>> names
['Alice', 'Beth', 'Dee-Dee', 'Earl']
>>> name = list('Perl') 
>>> name
['P', 'e', 'r', 'l']
>>> name[2:] = list('ar') 
>>> name
['P', 'e', 'a', 'r']
>>> numbers = [1, 2, 3, 4, 5]
>>> numbers[1:4] = []
>>> numbers
[1, 5]

列表方法

>>> lst = [1, 2, 3] 
>>> lst.append(4) 
>>> lst
[1, 2, 3, 4]
>>> list = [1, 2, 3] 
>>> list.clear()
>>> list
[]

这类似于切片赋值语句list[:] = []

>>> a = [1, 2, 3]
>>> b = a
>>> b[1] = 4  
>>> a
[1, 4, 3]
>>> a = [1, 2, 3] 
>>> b = a.copy() 
>>> b[1] = 4
>>> a
[1, 2, 3]
>>> ['to', 'be', 'or', 'not', 'to', 'be'].count('to') 2
>>> x = [[1, 2], 1, 1, [2, 1, [1, 2]]]
>>> x.count(1)
2
>>> x.count([1, 2])
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]
>>> x.pop(0)
1
>>> x [2]
>>> x = ['to', 'be', 'or', 'not', 'to', 'be'] 
>>> x.remove('be')
>>> x
['to', 'or', 'not', 'to', 'be']
>>> x = [1, 2, 3]
>>> list(reversed(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']
>>> x = [4, 6, 2, 1, 7, 9] 
>>> x.sort(reverse=True) 
>>> x
[9, 7, 6, 4, 2, 1]

元组:不可修改的序列

与列表一样,元组也是序列,唯一的差别在于元组是不能修改的(你可能注意到了,字符串 也不能修改)。元组语法很简单,只要将一些值用逗号分隔,就能自动创建一个元组。

>>> 1, 2, 3 
(1, 2, 3)
>>> (1, 2, 3) 
(1, 2, 3)

注意:元组只有一个值时,必须在它后面加上逗号。

>>> 42 
42
>>> 42,
 (42,)
>>> (42,)
 (42,)
>>> 3 * (42)
 126
>>> 3 * (42,)
 (42, 42, 42)

函数tuple的工作原理与list很像:它将一个序列作为参数,并将其转换为元组。如果参数已经是元组,就原封不动地返回它.

>>> tuple([1, 2, 3])
(1, 2, 3)
>>> tuple('abc') 
('a', 'b', 'c')
>>> tuple((1, 2, 3)) 
(1, 2, 3)

访问元组元素

>>> x = 1, 2, 3 
>>> x[1]
2
>>> x[0:2]
(1, 2)
上一篇 下一篇

猜你喜欢

热点阅读