Python入门(二)

时间:2022-10-22 03:58:57

Python版本:Python 2.7.5

1.列表切片

>>> numbers = [1,2,3,5,6,7,8]
>>> numbers[3]
5
>>> numbers[:3]
[1, 2, 3]
>>> numbers[-3:]
[6, 7, 8]
>>> numbers[:]
[1, 2, 3, 5, 6, 7, 8]

以上代码是步长默认为1情况下,也可以设置步长提取元素。
步长可以为正数,即是从左向右取值,如果为负数,即是从右向左取值
开始点的元素(最左边元素)包括在结果之中,而结束点的元素(最右边的元素)则不在结果之中,也就是数学中的半闭半开区间[)
对于一个正数步长,会从序列的头部开始向右提取元素,直到最后一个元素。
对于一个负数步长,会从序列的尾部开始向左提取元素,直到最开始一个元素。

>>> numbers[::2]
[1, 3, 6, 8]
>>> numbers[:6:2]
[1, 3, 6]
>>> numbers[:7:2]
[1, 3, 6, 8]
>>> numbers[3:7:-2]
[]
>>> numbers[::-2]
[8, 6, 3, 1]

2.序列的加法和乘法

>>> numbers+strs
[1, 2, 3, 5, 6, 7, 8, 'aaa', 'bbb', 'ccc']
>>> [1,2,3]+['hello']
[1, 2, 3, 'hello']
>>> [1,2,3]*2
[1, 2, 3, 1, 2, 3]

3.序列成员资格检查示例

Python入门(二)

4.内建函数

len返回序列中所包含元素的数量
max返回序列中最大的元素(也可以以多个数字作为参数)
min返回序列中最小的元素(也可以以多个数字作为参数)

>>> len(numbers)
7
>>> max(1,2,3,4)
4
>>> min(2,2,3,4)
2
>>> max(numbers)
8

5.NONE 空列表 初始化

空列表 可以用[]表示
初始化长度为10的空值

>>> emplyList = [None]* 10
>>> print emplyList
[None, None, None, None, None, None, None, None, None, None]

6.list函数

将数值中的内容全部列出来,不仅适用于字符串,还包括所有类型的序列

>>> list('nice')
['n', 'i', 'c', 'e']
>>> list([1,2,3,4,5])
[1, 2, 3, 4, 5]
>>> list(['a','b','c','d'])
['a', 'b', 'c', 'd']

7.对序列进行增删改查

>>> testList = [1,4,7,9,'Hello']
>>> testList[1]= 'world'
>>> print testList
[1, 'world', 7, 9, 'Hello']
>>> del testList[2]
>>> print testList
[1, 'world', 9, 'Hello']
#分片操作 非常强大,可以对序列进行添加,删除,修改等功能
>>> name = list('helloworld')
>>> print name
['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
>>> name[1:5]='i'
>>> print name
['h', 'i', 'w', 'o', 'r', 'l', 'd']
>>> name[1:3]=[]
>>> print name
['h', 'o', 'r', 'd']

8.count()方法统计某个元素在列表中出现的次数

extend()方法可以在列表的末尾一次性追加另一个序列的多个值,也就是用新列表扩展原有的列表

>>> ['a','b',['a','m'],'c','a'].count('a')
2
>>> print numbers
[1, 2, 3, 5, 6, 7, 8]
>>> addList = [4,9]
>>> numbers.extend(addList)
>>> print numbers
[1, 2, 3, 5, 6, 7, 8, 4, 9]
#该操作与numbers+addList不同,前者是扩展了numbers序列,而后者是创建了一个包含numbers和addList的新列表

9.pop()方法 会移除列表中的一个元素(默认是最后一个),并且返回该元素的值

该方法是唯一一个既能修改序列又能返回值的方法。

使用pop()方法实现栈---(后进先出)
append()进 pop()出

也可以用其他方法实现 先进先出
append()进 pop(0)出

10.remove()方法用于移除列表中某个值的第一个匹配项。该方法没有返回值

>>> ssby = ['to','be','or','not','to','be','is']
>>> ssby.remove('to');
>>> print ssby
['be', 'or', 'not', 'to', 'be', 'is']
>>> ssby.remove('hmlt')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in lis

11.reverse()方法 将列表中的元素反向存放

sort()方法用于在原位置对列表进行排序。就是改变原来的列表,而不是返回已排序的副本。

12.比较函数 cmp(x, y) 就需要两个参数,如果 x<y,返回 -1,如果 x==y,返回 0,如果 x>y,返回 1:

int()函数可以把其他数据类型转换为整数
str()函数把其他类型转换成 str

Python入门(二)

部分内容来源于书籍 《Beginning.Python.From.Novice.to.Professional,2nd.Edition》