python快速上手_第四章 列表

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mike_Cui_LS/article/details/83144513

列表数据类型

Python 中的列表,与 java中的 数组比较像。[] 包含, 以 “,”分隔, 通过下标取元素,下标以 0 开始。

列表是一个值, 它包含多个值构成的序列。

>>> [1,2,3]
[1, 2, 3]
>>> ['cat','bat','rat','elephant']
['cat', 'bat', 'rat', 'elephant']
>>> ['hello',3.1415,True,None,42]
['hello', 3.1415, True, None, 42]
>>> spam = ['cat','bat','rat','elephant']
>>> spam
['cat', 'bat', 'rat', 'elephant']

用下标取得列表中的单个值

和java中数组的取值方式相同,而且 下标也是从 0 开始。

>>> spam = ['cat','bat','rat','elephant']
>>> spam
['cat', 'bat', 'rat', 'elephant']
>>> spam[0]
'cat'
>>> spam[1]
'bat'
>>> 'Helllo'+spam[0]
'Helllocat'
>>> 'The ' +spam[1] + ' ate the '+spam[0]
'The bat ate the cat'

如果下标超出列表中的个数。Python将给出 IndexError 出错信息。

>>> spam[10]
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    spam[10]
IndexError: list index out of range

下标超出范围

列表中也可以包含其他的列表,类似java中的 多元数组

>>> spam = [['cat','bat'],[10,20,30,40,50]]
>>> spam[0][1]
'bat'
>>> spam[1][2]
30

负数下标

也可以用负整数来作为下标。整数值 -1 指的是列表中的最后一个下标; -2指的是列表中的倒数第二个下标,以此类推

>>> spam = ['a','b','c','d']
>>> spam[-1]
'd'
>>> spam[-2]
'c'

利用切片取得子列表

“切片“ 可以从列表中取得多个值,结果是一个新列表。

spam[1:4] 是一个列表和切片

第一个整数是切片开始处的下标,第二个整数是切片结束处的下标。包前不包后。结果为一个新的列表。

>>> spam = ['a','b','c','d']
>>> spam[-1]
'd'
>>> spam[-2]
'c'
>>> spam
['a', 'b', 'c', 'd']
>>> spam[0:4]
['a', 'b', 'c', 'd']
>>> spam[1:3]
['b', 'c']
>>> spam[0:5]
['a', 'b', 'c', 'd']
>>> spam[0:10]
['a', 'b', 'c', 'd']
>>> spam[-1:2]
[]

省略第一个整数, 代表从 0 开始,或者列表的开始。 省略第二个整数 代表 到列表的结束。

>>> spam = ['cat','bat','rat','elephant']
>>> spam
['cat', 'bat', 'rat', 'elephant']
>>> spam[:2]
['cat', 'bat']
>>> spam[1:]
['bat', 'rat', 'elephant']
>>> spam[:]
['cat', 'bat', 'rat', 'elephant']

len 取得列表的长度

len()函数 将返回传递给它的列表的值的个数。

>>> spam
['cat', 'bat', 'rat', 'elephant']
>>> len(spam)
4

用下标来改变列表中的值

可以使用列表的下标来改变下标处的值。

>>> spam
['cat', 'bat', 'rat', 'elephant']
>>> spam[1] = 'dog'
>>> spam
['cat', 'dog', 'rat', 'elephant']
>>> spam[2] = spam[1]
>>> spam
['cat', 'dog', 'dog', 'elephant']
>>> spam[-1] = 123
>>> spam
['cat', 'dog', 'dog', 123]

列表的拼接和复制

可以使用 + 符号来连接两个列表,就如同连接两个字符串那样。

使用 一个 列表 和 * 符号来实现复制列表的功能。

>>> [1,2,3] + ['A','B','C','D']
[1, 2, 3, 'A', 'B', 'C', 'D']
>>> [1,2,3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> spam = ['d','e','f']
>>> spam + ['A','B']
['d', 'e', 'f', 'A', 'B']

使用 del 来删除列表中的值

使用del来删除指定列表下的值,删除后,该下标后面的元素都向前移动一个下标。

>>> spam
['d', 'e', 'f']
>>> del spam[0]
>>> spam
['e', 'f']
>>> del spam[1]
>>> spam
['e']
>>> del spam[-1]
>>> spam
[]

使用列表

之前,我们说到了用变量来存储数据。 但是,如果数据量大了呢? 就会出现大量的变量,重复的内容。而且新增等操作起来极其麻烦,还得再增加代码。

我们可以使用列表来存储这些相似的数据。 比如以下:

catNames = []
while True:
    print('Enter the name of cat '+str(len(catNames) + 1) + ' (Or enter nothing to stop.)')
    name = input()
    if name =='':
        break
    catNames = catNames+[name]

print('The cat names are : ')

for name in catNames:
    print(' '+name)
    

列表用于循环

for i in range(4):
    print(i)
    

0 
1
2
3

range(4) 的返回值类似列表的值,python认为它类似于[0,1,2,3].

让变量依次设置为 列表中的值。

一个比较常见的技巧是在 for 循环中使用 range(len(somelist)) 获取到每一个下标,然后可以通过 somelist[index]的方式,获取到每一个值。

两种遍历方式如下:

>>> supplies = ['pens','staplers','binders','rulers']
>>> for i in supplies:
	print('Index '+i)

Index pens
Index staplers
Index binders
Index rulers
>>> for i in range(len(supplies)):
	print('Index : '+str(i) + ' in supplies is : '+supplies[i])

Index : 0 in supplies is : pens
Index : 1 in supplies is : staplers
Index : 2 in supplies is : binders
Index : 3 in supplies is : rulers

in和not in 操作符

in 和 not in 类似于 java 中的 contians 。 判断一个值是否在一个列表中, 如果存在,则返回True ; 否则返回false.

>>> 'a' in ['a','b','c']
True
>>> 'a' not in ['a','b','c']
False
>>> letters = ['a','b','c']
>>> 'b' not in letters
False

下面的例子来判断,宠物是否在列表中:

myPets = ['Zophie','Pooka','Fat']

print('Enter a pet Name : ')

name = input()

if name in myPets:
    print(name + ' is my pet ')
else:
    print('I do not have a pet Named : '+name )

多重赋值技巧

是一种快捷的赋值方式, 用列表中的值为变量赋值; 要求列表中的值个数 和 变量的个数相同。 否则会报出 ValueError的错误.

>>> cat = ['fat','black','loud']
>>> size = cat[0]
>>> color = cat[1]
>>> disposition = cat[2]
>>> size
'fat'
>>> 
>>> size,color,disposition = cat
>>> color
'black'

当列表的值的个数和变量个数不用的时候:

>>> size,color = cat
Traceback (most recent call last):
  File "<pyshell#82>", line 1, in <module>
    size,color = cat
ValueError: too many values to unpack (expected 2)

增强的赋值操作

>>> spam = 42
>>> spam = spam + 1
>>> spam
43

上面的赋值操作,可以替换为:

>>> spam = 42
>>> spam += 1
>>> spam
43

用 += 来完成同样的事情。

针对 + - * / % 操作符, 都有增强操作符。

spam += 1              spam = spam+1

spam -= 1              spam = spam-1

spam *= 1              spam = spam*1

spam /= 1              spam = spam/1

spam %= 1              spam = spam%1

+= 操作符同样可用于字符串, *=操作符同样可用于 字符串和列表的复制

>>> spam = 'hello '
>>> spam+='world'
>>> spam
'hello world'
>>> bacon = ['abc']
>>> bacon*=3
>>> bacon
['abc', 'abc', 'abc']

方法

方法和函数其实是一回事,只是方法调用在一个值上。比如 java中对于字符串操作的 substring()、split()等, 在python中也是一样的操作方式。

用index()方法在列表中查找值

index() 方法传入一个值, 如果该值在列表中,就返回该值的下标.如果不存在,则会报错。

>>> spam = ['hello','world','abc']
>>> spam.index('hello')
0
>>> spam.index('abc')
2
>>> spam.index('def')
Traceback (most recent call last):
  File "<pyshell#107>", line 1, in <module>
    spam.index('def')
ValueError: 'def' is not in list

如果列表中有重复的值,就返回第一次出现的下标。

>>> spam = ['a','b','d','a','a']
>>> spam.index('a')
0

用append 和 insert 方法在列表中添加值

在列表中添加新值.使用append() 和 insert方法。

>>> spam = ['hello','world','ni']
>>> spam.append('hao')
>>> spam
['hello', 'world', 'ni', 'hao']

append()方法时在列表的后面添加一个值, 而 insert 是在列表的任意位置添加一个值。

>>> spam = ['hello','ni']
>>> spam.insert(1,'world')
>>> spam
['hello', 'world', 'ni']
>>> spam.insert(2,'world')
>>> spam
['hello', 'world', 'world', 'ni']
>>> spam.insert(4,'hao')
>>> spam
['hello', 'world', 'world', 'ni', 'hao']

append()和insert() 都是列表方法,不能在其他的值上面调用

>>> spam = 'Hello'
>>> spam.append(' World')
Traceback (most recent call last):
  File "<pyshell#134>", line 1, in <module>
    spam.append(' World')
AttributeError: 'str' object has no attribute 'append'

用remove方法移除列表中的值

往remove()方法中传递一个值, 将试图从列表中删除,如果存在则删除,如果不存在 则报错 ValueError.

>>> spam = ['cat','dog','snake','mouse']
>>> spam.remove('cat')
>>> spam
['dog', 'snake', 'mouse']
>>> spam.remove('elephant')
Traceback (most recent call last):
  File "<pyshell#141>", line 1, in <module>
    spam.remove('elephant')
ValueError: list.remove(x): x not in list

如果列表中有多个相同的值,那么只有第一次出现的值才会被删除。

>>> spam = ['a','b','a','c']
>>> spam.remove('a')
>>> spam
['b', 'a', 'c']

删除有两种方法:

  • del,在知道要删除值的下标的情况下。
  • remove,在知道要删除的值的情况下。
>>> spam
['b', 'a', 'c']
>>> del(spam[1])
>>> spam
['b', 'c']

用 sort()方法将列表中的值排序

数值的列表 和 字符串的列表,可以用 sort()排序, 也可以指定 reverse 关键字参数为True,让 sort 按逆序排序

>>> spam = [3,2,-1,10,28,12,15]
>>> spam.sort()
>>> spam
[-1, 2, 3, 10, 12, 15, 28]
>>> 
>>> spam = ['hello','Alice','Eirc','Bob']
>>> spam.sort
<built-in method sort of list object at 0x112146988>
>>> spam.sort()
>>> spam
['Alice', 'Bob', 'Eirc', 'hello']

逆序排序
>>> spam.sort(reverse = True)
>>> spam
['hello', 'Eirc', 'Bob', 'Alice']

用sort方法排序,需要注意一下几点:

  • sort()方法当场对列表排序,不要写出 spam = spam.sort()这样的代码。
  • 不能对既有数字又有字符串的列表排序,因为python不知道如何比较他们。(示例见下面)
  • sort()方法对字符排序时,使用的是‘ASCII字符顺序’,而不是实际的字典顺序。以为着大写字母排在小写字母之前。如果需要按字典顺序来排序的话,可以给 sort方法指定关键字参数 key 设置为 str.lower。排序的时候会把所有的字母当成小写,而并不会实际改变列表中的值。

第二条 示例:

>>> spam = ['a','b',1,2,'c']
>>> spam.sort()
Traceback (most recent call last):
  File "<pyshell#169>", line 1, in <module>
    spam.sort()
TypeError: '<' not supported between instances of 'int' and 'str'

第三条 示例:

>>> spam = ['a','C','Z','b','E']
>>> spam.sort()
>>> spam
['C', 'E', 'Z', 'a', 'b']
>>> spam.sort(key = str.lower)
>>> spam
['a', 'b', 'C', 'E', 'Z']

神奇8球

# magic8Ball2 program

import random

messages = ['First','Second','Third','Fourth','FiFth','Sixth','Seventh']

print(messages[random.randint(1,len(messages)-1)])

在列表中保存了我们的数据, 然后生成随机数,获取对于的数值并打印。

python中的缩进规则的例外

多数情况下,代码行的缩进告诉python它属于哪个代码块。但是有几个例外。

1.在源码文件中,列表可以跨越几行,这些行的缩进并不重要。python认为没有看到方括号,列表就没有结束。

spam = ['a',


        'b',

            'c']

print(spam)

2.也可以在行末使用续行字符 \ .将一条指令写成多行。可以把 “\” 看成是“这条指令在下一行继续”。

print('hello'+\
      'world')

类似列表的数据类型:字符串和元组

字符串和列表很相似, 可以认为字符串是单个文本字符的列表。 很多用于列表的操作,都可以用于字符串: 按下标取值、切片、for循环、用于len(),以及in和not in操作符。

>>> name = 'helloworld'
>>> name[0]
'h'
>>> name[-2]
'l'
>>> name[0:4]
'hell'
>>> 'wo' in name
True
>>> 'or' in name
True
>>> 'cd' in name
False
>>> for i in name:
	print('........'+i +'........')

........h........
........e........
........l........
........l........
........o........
........w........
........o........
........r........
........l........
........d........

可变和不可变数据类型。

列表是可变的,字符串是不可变的。 这里和java中的有些类似,java中的字符串也是不可变的;但可以重新赋值一个新的字符串。

>>> name = 'Hello a world'
>>> name[6] = 'abc'
Traceback (most recent call last):
  File "<pyshell#197>", line 1, in <module>
    name[6] = 'abc'
TypeError: 'str' object does not support item assignment

因为字符串是不可变的,所以会报错。可以通过下面的方式来创建一个新的字符串:

>>> name
'Hello a world'
>>> newName = name[0:6] + 'abc'+name[7:]
>>> newName
'Hello abc world'

列表值时可变的,但对于下面的代码,却并没有修改列表,只是重新赋值,覆写了列表。

>>> eggs = [1,2,3]
>>> eggs = [4,5,6]
>>> eggs
[4, 5, 6]

如果确实想修改列表,可以通过列表的方法来操作, 比如 append,remove,del等等。

>>> eggs = [1,2,3]
>>> eggs.remove(1)
>>> eggs
[2, 3]
>>> eggs.append(4)
>>> eggs
[2, 3, 4]
>>> del eggs[0]
>>> eggs
[3, 4]
>>> eggs.insert(0,5)
>>> eggs
[5, 3, 4]

元组数据类型

元组数据类型和列表数据类型几乎一样。

不同点在于:

  • 元组输入用(),列表用[]
>>> eggs = ('hello','world',21,31)
>>> eggs
('hello', 'world', 21, 31)
>>> eggs[2]
21
>>> eggs[1:3]
('world', 21)
>>> len(eggs)
4
  • 元组像字符串一样,是不可变的,它的值不能被修改、添加、或删除。
>>> eggs = (1,3,5,10,23)
>>> eggs
(1, 3, 5, 10, 23)
>>> eggs[0] = 20
Traceback (most recent call last):
  File "<pyshell#233>", line 1, in <module>
    eggs[0] = 20
TypeError: 'tuple' object does not support item assignment

如果元组中只有一个值,那么需要在该值后面加入一个 “,” 。 否则python 就会认为是一个普通括号内输入了一个值。 逗号告诉python 这是一个元组。

>>> type(('hello',))
<class 'tuple'>
>>> type(('hello'))
<class 'str'>

使用元组因为他是不可变的,内容不会变化,Python可以实现一些优化,让使用元组的代码比使用列表的代码更快。

用list() 和 tuple()来转换类型

list() 返回传给它们的值的列表。

tuple() 返回传递给他们的值的元组。

>>> spam = ('hello','world',1,3)
>>> spam
('hello', 'world', 1, 3)
>>> list(spam)
['hello', 'world', 1, 3]
>>> tuple(['cat','dog'])
('cat', 'dog')
>>> list('hello')
['h', 'e', 'l', 'l', 'o']

如果需要一个元组的可变版本,那么可以将元组转换为列表。

引用

这里的类似于java 中的,值传递和引用传递。

对于int、float等 变量保存的是值, 而对于列表、元组 变量保存的是引用。

对比下面两个例子:

值传递:

>>> spam = 42
>>> cheese = spam
>>> cheese
42
>>> spam = 100
>>> spam
100
>>> cheese
42

引用传递:

>>> spam = ['hello','world','a','b']
>>> cheese = spam
>>> cheese
['hello', 'world', 'a', 'b']
>>> cheese[1] = 'def'
>>> cheese
['hello', 'def', 'a', 'b']
>>> spam
['hello', 'def', 'a', 'b']

传递引用

对于函数,引用参数,当函数被调用时,参数的值被复制给变元(形参)。对于列表,变元获取到的是 列表引用的拷贝。

def process(eggsData):
    eggsData[0] = '123'

eggs = ['a','b','c']

process(eggs)

print(eggs)

copy模块的 copy()和 deepcopy()函数

这里类似Java中的 浅拷贝和深拷贝。

在使用函数前,首先需要 import copy .

copy()用来复制列表或字典这样的可变值,而不知是引用。

deepcopy() 用来复制 列表中包含列表的情况。

import copy

spam = ['a','b','c']

cheese = copy.copy(spam)

cheese[1] = 42

print(spam)

print(cheese)

输出结果:
['a', 'b', 'c']
['a', 42, 'c']

小结

  • 列表可以存储很多数据,并且只有一个变量
  • 列表时可变的,元组和字符串虽然某些方面像列表,但是是不可变的。
  • 包含一个元组的或者字符串的变量,可以被一个新的元组或字符串复写,直接把引用修改了。 和 append,remove方法的修改,不是一回事。
  • 变量不直接保存列表的值,保存的是对列表的引用。
  • 需要对一个变量中的列表修改,同时不修改原来的列表,可以使用 copy 和 deepcopy()

猜你喜欢

转载自blog.csdn.net/mike_Cui_LS/article/details/83144513