Python入门篇之列表和元组

2019-10-05 15:30:36丽君

 测试代码
序列相加

通过使用加号可以进行序列的连接操作:


>>> [1,2,3]+[4,5,6]
[1, 2, 3, 4, 5, 6]
>>> 'hello.'+'world!'
'hello.world!'
>>> [1,2,3]+'world!'

Traceback (most recent call last):
  File "<pyshell#107>", line 1, in <module>
    [1,2,3]+'world!'
TypeError: can only concatenate list (not "str") to list

乘法

用数字x乘以一个序列会生成新的序列,而在新的序列中,原来的序列将被重复x次


>>> 'python'*5
'pythonpythonpythonpythonpython'
>>> [42]*10
[42, 42, 42, 42, 42, 42, 42, 42, 42, 42]

成员资格

为了检查一个值是否在序列中,可以使用in运算符,该运算符返回布尔值


>>> permissions='rw'
>>> 'w'in permissions
True
>>> 'x'in permissions
False
Enter your name: mlh
True
>>> subject='$$$ Get rich now!!! $$$'
>>> '$$$'in subject
True

长度、最小值和最大值

内建函数len、min、max,len函数返回序列中所包含元素的数量,min和max函数分别返回序列中最大和最小的元素


>>> numbers=[100,34,678]
>>> len(numbers)
3
>>> max(numbers)
678
>>> min(numbers)
34
>>> max(2,3)
3
>>> min(9,3,2,5)
2

list函数

list函数可以根据字符串创建列表


>>> list('hello')
['h', 'e', 'l', 'l', 'o']

基本列表操作:
1、改变列表:元素赋值

使用索引标记来为某个特定的、位置明确的元素赋值:


>>> x=[1,1,1]
>>> x[1]=2
>>> x
[1, 2, 1]

2、删除元素

使用del语句来实现:


>>> names=['Alice','Beth','Ceil','Dee-Dee','Earl']
>>> del names[2]
>>> names
['Alice', 'Beth', 'Dee-Dee', 'Earl']

注意:Cecil是彻底删除,列表长度也从5变为4

3、分片赋值

 View Code
列表方法:

方法是一个与某些对象有紧密联系的函数,对象可能是列表、数字,也可能是字符串或者其他类型的对象,方法的调用方式:对象.方法(参数)

1、append

append方法用于在列表末尾追加新的对象:


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

2、cout

count方法用于统计某个元素在列表中出现的次数:


>>> ['to','be','or','not','to','be'].count('to')