python基础笔记4

根据参考书《Python编程快速上手》进行入门学习的,这本书写得真不错,翻译质量感觉也相当好

列表数据类型

列表用左方括号开始,右方括号结束,列表中的值称为表项,表项用逗号分隔

>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam
['cat', 'bat', 'rat', 'elephant']

下标取得列表中的单个值,第一个表项的下标是0,下标超出范围–IndexError

>>> spam[0]
'cat'
>>> spam[4]
Traceback (most recent call last):
  File "", line 1, in 
    spam[4]
IndexError: list index out of range

列表也可以包含其他列表,访问列表中列表的表项,可以通过多重下标

>>> spam = [ ['cat','bat'], [10,20,30,40,50]]
>>> spam[0]
['cat', 'bat']
>>> spam[1][0]
10
>>> spam[1][4]
50
>>> spam[0][4]
Traceback (most recent call last):
  File "", line 1, in 
    spam[0][4]
IndexError: list index out of range

负数下标,整数-1指列表中最后一个项,-2指倒数第二个,依次类推

>>> spam[-1]
[10, 20, 30, 40, 50]
>>> spam[-1][-2]
40

利用切片取得子列表
- spam[2] 一个列表和下标
- spam[1:4] 一个列表和切片(第一个为开始的下标,第二个为结束,但不包括它)
- 冒号不能省略,切片中省略第一个下标相当于使用0,省略第二个下标相当于使用列表长

>>> spam = [10, 20, 30, 40, 50]
>>> spam[3:]
[40, 50]
>>> spam[:3]
[10, 20, 30]

用len()函数取得列表的长度

>>> len(spam)
5

用下标访问改变列表对应下标处的值

>>> spam[0] = 'a'
>>> spam
['a', 20, 30, 40, 50]

列表连接和列表复制
- +操作符可以连接两个列表
- *操作符可以用于一个列表和一个整数,实现列表复制整数次

>>> [1,2,3] + ['a','bb',"ccc"]
[1, 2, 3, 'a', 'bb', 'ccc']
>>> spam = [1, 2, 3, 'a', "aaa"]
>>> spam *= 3
>>> spam
[1, 2, 3, 'a', 'aaa', 1, 2, 3, 'a', 'aaa', 1, 2, 3, 'a', 'aaa']

del语句从列表中删除值,被删除值后面的所有值都将向前移动
- del语句也删除简单变量,删除之后试图使用–NameError,实践中几乎永远不需要删除简单变量。

>>> spam
[1, 2, 3, 'a', 'aaa', 1, 2, 3, 'a', 'aaa', 1, 2, 3, 'a', 'aaa']
>>> del spam[11]
>>> spam
[1, 2, 3, 'a', 'aaa', 1, 2, 3, 'a', 'aaa', 1, 3, 'a', 'aaa']
>>> del spam[2:10]
>>> spam
[1, 2, 1, 3, 'a', 'aaa']

使用列表

列表保存一组类似的值

#!/usr/bin/env python3
# coding=utf-8
catNames = []
while True:
    print('Enter the name of cat '+str(len(catNames)+1)+' Or nothing exit')
    name = input()
    if name == '':
        break
    catNames = catNames + [name]  # list concatenation
print('The cat names are:')
for name in catNames:
    print(' '+name, end=' ')

列表用于循环
- range()函数的返回值是类似列表的值,range(0,10,3)类似于[0,3,6,9]
- 常在for循环中使用range(len(someList))迭代列表中的每一个下标

>>> supplies = ['aa','bb','cc','dd']
>>> for i in range(len(supplies)):
    print('Index',str(i),'is',supplies[i])


Index 0 is aa
Index 1 is bb
Index 2 is cc
Index 3 is dd

in和not in操作符
- 要在列表中查找的值 in/not in 待查找列表

#!/usr/bin/env python3
# coding=utf-8
myPets = ['zophie', 'pooka', 'fat-tail']
print('Enter a pet name:')
name = input()
if name in myPets:
    print(name, 'is my pet')
else:
    print(name, "is'not my pet")

多重赋值技巧,注意变量的数目和列表的长度必须严格相等,否则ValueError

>>> cat = ['fat','black','loud']
>>> size, color, disposition = cat
>>> size
'fat'
>>> color
'black'
>>> disposition
'loud'
>>> size, color = cat
Traceback (most recent call last):
  File "", line 1, in 
    size, color = cat
ValueError: too many values to unpack (expected 2)
>>> size,cat = cat[:2]
>>> size
'fat'
>>> cat
'black'

方法

每种数据类型都有它自己的一组方法,比如列表有查找、添加、删除、操作列表中的值等
1. index()方法在列表中查找值,若查找的值在列表中,返回它的下标(若存在多个该值,则返回第一次出现的下标),否则ValueError

>>> spam = ['aa', 'bb', 10, 20]
>>> spam.index('bb')
1
>>> spam.index('cc')
Traceback (most recent call last):
  File "", line 1, in 
    spam.index('cc')
ValueError: 'cc' is not in list
  1. append()添加新值到末尾,insert()方法在指定下标处插入一个值
>>> spam = ['cat', 'dog', 'bat']
>>> spam.append('pooka')
>>> spam
['cat', 'dog', 'bat', 'pooka']
>>> spam.insert(1,'chicken')
>>> spam
['cat', 'chicken', 'dog', 'bat', 'pooka']
  1. remove()从列表中删除值,试图删除不存在的值–ValueError。如果该值出现多次,只有第一个出现的值被删除;如果知道要删除值的下标,del语句更好用
>>> spam.remove('cat')
>>> spam
['chicken', 'dog', 'bat', 'pooka']
>>> spam.remove('abc')
Traceback (most recent call last):
  File "", line 1, in 
    spam.remove('abc')
ValueError: list.remove(x): x not in list
  1. sort()将列表中的值排序,对字符串使用ASCII字符顺序,不是字典序,可以指定reverse关键字为True–逆序排序,指定key关键字为str.lower来进行字典排序。不能对既有数字,又有字符串的列表进行排序
>>> spam = [2,5,3.14,1,5,-7,6,2]
>>> spam.sort()
>>> spam
[-7, 1, 2, 2, 3.14, 5, 5, 6]
>>> spam.sort(reverse=True)
>>> spam
[6, 5, 5, 3.14, 2, 2, 1, -7]
>>> spam = ['aa','bc','abc','AA','BC','ABC']
>>> spam.sort()
>>> spam
['AA', 'ABC', 'BC', 'aa', 'abc', 'bc']
>>> spam.sort(key=str.lower)
>>> spam
['AA', 'aa', 'ABC', 'abc', 'BC', 'bc']
>>> spam = ['aa','bc','cd','AA','BC',1,3,5,7,2]
>>> spam.sort()
Traceback (most recent call last):
  File "", line 1, in 
    spam.sort()
TypeError: unorderable types: int() < str()

Python中缩进规则的例外

大多数情况下,代码行的缩进告诉python它属于哪一个代码块。但是
1. 列表可以跨越几行,这些行的缩进不重要(没有看到右方括号,列表就未结束)
2. 行末使用续行字符\,将一条指令分为多行,续行之后的一行中,缩进不重要

>>> spam = ['apples', 'oranges',
    'bananas',
'cats']
>>> spam
['apples', 'oranges', 'bananas', 'cats']
>>> print('For score and seven '+\
      'years'+\
        'ago' )
For score and seven yearsago

类似列表的类型–字符串

可以对字符串:按下标取值,切片,用于for循环,len(),in和not in操作符

>>> name = 'hello world'
>>> name[0]
'h'
>>> name[-1]
'd'
>>> name[2:4]
'll'
>>> 'or' in name
True
>>> for i in name:
    print('*'+i+'*',end=' ')


*h* *e* *l* *l* *o* * * *w* *o* *r* *l* *d*

注意,列表是“可变的”数据类型–可以对它进行添加、删除和改变,字符串是“不可改变的”,不能被更改,尝试对字符串中的字符进行修改–TypeError错误

>>> name = 'hello world'
>>> name[0] = 'H'
Traceback (most recent call last):
  File "", line 1, in 
    name[0] = 'H'
TypeError: 'str' object does not support item assignment
>>> newName = 'H'+name[1:6]+'W'+name[7:]
>>> newName
'Hello World'

注意以下语句是列表的覆写,新的列表值覆写了旧的列表值,不是修改了列表

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

列表的修改

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

类似列表的数据类型–元组

元组和列表几乎一样,除了:
- 元组是左圆括号开始,右圆括号结束,(‘hello’, 1, 2)
- 元组和字符串一样,都是不可变的,不能被修改、添加和删除
- 元组中有一个值时,要在括号内该值后面跟上一个逗号,表明是元组,否则Python认为是普通圆括号内输入一个值,type()函数可以查看值的类型;列表中只有一个值,放在方括号中,即可表明这是列表

>>> eggs = ('hello', 1, 2)
>>> eggs[0]
'hello'
>>> eggs[1] = 2
Traceback (most recent call last):
  File "", line 1, in 
    eggs[1] = 2
TypeError: 'tuple' object does not support item assignment
>>> type(('hello',))
<class 'tuple'>
>>> type(('hello'))
<class 'str'>
>>> type(['hello'])
<class 'list'>
>>> type(['hello',])
<class 'list'>

list()和tuple()函数来回转换类型

>>> tuple(['aa','bb',1,2])
('aa', 'bb', 1, 2)
>>> list(('aa','bb',1,3.14))
['aa', 'bb', 1, 3.14]
>>> list((1,))
[1]
>>> tuple([1])
(1,)

引用

变量就像包含着值的盒子。列表的赋值使用的是引用–指向一个列表的值
- 变量保存可变数据类型的值(比如列表、字典),Python就使用引用
- 变量保存不可变数据类型的值(比如字符串、数值、元组),Python就保存值本身

>>> spam = 42
>>> cheese = spam
>>> spam = 100
>>> spam
100
>>> cheese
42
>>> spam = [1,2,3,4,5]
>>> cheese = spam
>>> cheese.append('Hello world')
>>> spam
[1, 2, 3, 4, 5, 'Hello world']
>>> cheese
[1, 2, 3, 4, 5, 'Hello world']

函数中的列表参数传递的是引用

#!/usr/bin/env python3
# coding=utf-8
def eggs(someList):
    someList.append('Hello')

spam = [1,2,3,4]
eggs(spam)
print(spam)  #输出[1, 2, 3, 4, 'Hello']

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

处理列表或字典事,尽管传递引用很方便,这可能修改了传入的列表或字典。如果不希望修改传入的列表或字典,就需要使用copy.copy()和copy.deepcopy()函数,后者用于多重列表

>>> import copy
>>> spam = ['A','b','C','d']
>>> cheese = copy.copy(spam)
>>> cheese[1] = 42
>>> spam
['A', 'b', 'C', 'd']
>>> cheese
['A', 42, 'C', 'd']
>>> spam=[[1,2,3],['a','bb','cc']]
>>> cheese = copy.copy(spam)
>>> cheese[1][2] = 'hello world'
>>> cheese
[[1, 2, 3], ['a', 'bb', 'hello world']]
>>> spam
[[1, 2, 3], ['a', 'bb', 'hello world']]
>>> cheese = copy.deepcopy(spam)
>>> cheese[1][2] = 'changed'
>>> cheese
[[1, 2, 3], ['a', 'bb', 'changed']]
>>> spam
[[1, 2, 3], ['a', 'bb', 'hello world']]

你可能感兴趣的:(python3)