编程语言
首页 > 编程语言> > Python Crash Course读书笔记 - 第3章:INTRODUCING LISTS

Python Crash Course读书笔记 - 第3章:INTRODUCING LISTS

作者:互联网

什么是List

List是一些项的有序(注意不是排序)集合,用方括号([])表示,其中的项(也称为成员)用逗号(,)分开。List变量名通常用复数。
List中可以有重复值。
List中的成员可以混合不同类型,但本章的示例都是同类型的。
项目的索引由0开始,这和C语言是一样的。

>>> months = ['jan', 'feb', 'march', 'may']
>>> print(months)
['jan', 'feb', 'march', 'may']
>>> print(months[0] + ' ' + months[1])
jan feb
>>> print(months[0].title());
Jan

索引-1可表示最后一项,符号表示从右边往回数:

>>> print(months[-1])
may
>>> print(months[-2])
march

增删改成员

>>> print (months)
['Jan', 'feb', 'march', 'may']
# 追加
>>> months.append('dec');
>>> print (months)
['Jan', 'feb', 'march', 'may', 'dec']
# 插入,3即index
>>> months.insert(3,'apr')
>>> print (months)
['Jan', 'feb', 'march', 'apr', 'may', 'dec']
# 修改
>>> months[-1]='DEC'
>>> print (months)
['Jan', 'feb', 'march', 'apr', 'may', 'DEC']
# 删除,很奇怪del居然不是method
>>> del months[-1]
>>> print (months)
['Jan', 'feb', 'march', 'apr', 'may']

还有一种特殊的移除成员方式,利用pop()方法:

# 默认删除最后一个成员,注意poped_month是单数
>>> poped_month = months.pop()
>>> print(months)
['Jan', 'feb', 'march', 'apr']
>>> print(poped_month)
may
# 也可pop指定的成员
>>> poped_month = months.pop(0)
>>> print(months)
['feb', 'march', 'apr']
>>> print(poped_month)
Jan

也可根据成员的值(可以指定常数或变量)来删除, 但remove()只删除第一个匹配的值。:

>>> months.remove('march')
>>> print(months)
['feb', 'apr']

清空List:

>>> months=[]
>>> print(months)
[]

组织List

排序:

>>> months = [ 2, 5, 9, 1, 3, 10]
#正向排序
>>> months.sort()
>>> print(months)
[1, 2, 3, 5, 9, 10]

# 反向排序,注意True区分大小写,不能写成true
>>> months.sort(reverse=True)
>>> print(months)
[10, 9, 5, 3, 2, 1]

使用sorted函数临时排序,不会改变源List:

>>> months = [ 2, 5, 9, 1, 3, 10]
>>> print(sorted(months))
[1, 2, 3, 5, 9, 10]
>>> print(sorted(months, reverse=True))
[10, 9, 5, 3, 2, 1]
>>> print(months)
[2, 5, 9, 1, 3, 10]

注意sorted()是函数,函数是有返回值的,因此可以打印。而sort()是method,没有返回值。后面的len()也是函数。method前面会跟对象,并通过’.'调用。

颠倒顺序:

>>> print(months)
[2, 5, 9, 1, 3, 10]
>>> months.reverse()
>>> print(months)
[10, 3, 1, 9, 5, 2]

计算List的成员数量:

>>> len(months)
6

避免Index错误

也就是避免index超限:

>>> print(months[6])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

如List为空,索引为-1也会超限。

dingdingfish 博客专家 发布了352 篇原创文章 · 获赞 42 · 访问量 55万+ 他的留言板 关注

标签:INTRODUCING,feb,Crash,读书笔记,months,List,print,march,10
来源: https://blog.csdn.net/stevensxiao/article/details/103973416