Python 学习笔记: List

python学习网 2021-02-22 17:44:02

也许和大多数普通人一样,我经历了一个特别的2020年。手足无措,浑浑噩噩,整顿修养。

终于2021年万物复苏的春天,我把自己支楞了起来,重新开始学习和记录。第一步打算系统整理或者说复习 Python。以前因为工作断断续续地学习,自己了解的知识都是七零八落的,写起代码就是东拼西凑的。

希望这次的复习能得个全貌。

List

list 是容器数据类型(collection)的其中一种,它允许在一个变量中存放多个数值。

List Constants

list 可以存放任意 Python 数据类型,例如 number,string,character,甚至是 list。

list = [] #empty list
list = [1, 2, 3, 4]
list = ['a', 'b', 'c', 'd']
list = ["apple", "banana", "cat", "dog"]
list = [1, [2, 3], 4]

与 string 类似,list 也可以利用 indexing 获取 list 中某个值,如:

list = [1, 2, 3, 4]
print(list[2])
>> 3

但是和 string 不一样的是, list 的值是可以修改的,而 string 的值是不可以修改的。

list = ['a', 'p', 'p', 'l', 'e']
list[2] = 'x'
print(list)
>> ['a', 'p', 'x', 'l', 'e']

List Manipulating

对连接或者分割 list,有两个重要的符号,分别是 “+” 和 “:”。

“+” 是用于连接两个 list, 如:

a = [1, 2]
b = [3, 4]
list = a + b
print(list)
>> [1, 2, 3, 4]

“:” 是用于分割 list的, 如:

list = [1, 2, 3, 4, 5]
sublist = list[1:3] #from index = 1 to index = 3-1
print(sublist)
>> [2, 3]
sublist = list[:3] #from index = 0 to index = 3-1
print(sublist)
>> [1, 2, 3]
sublist = list[1:] #from index = 1 to index = len(list) -1
print(sublist)
>> [2, 3, 4, 5]

List Methods

列举几个常用的 methods.

  • append:增加新的值
  • in:检查 list 是否包含某个值
list = [1, 2, 3, 4]
print(9 in list)
>> False
  • sort:对 list 的值进行排序
  • len:计算 list 的长度
  • maxminsum:计算 list 的最大值,最小值以及总和

List and Loop

如果需要遍历 list 中的每一个值也很简单,我们可以利用 for:

list = [1, 2, 3, 4, 5]
for ii in list:
    print(ii)

也可以利用 for 和 range() 遍历 list 中的 index,从而获取 list 的值:

list = [1, 2, 3, 4, 5]
for ii in range(len(list)):
    print(list[ii])
阅读(2421) 评论(0)