目录
第1章、基础知识
1.字符串和元组属于不可变序列,这意味着不能通过下标的形式来修改其中的元素值,例如下面代码会抛出异常:
>>>x=(1,2,3)
>>>print(x)
(1,2,3)
>>>x[1]=5
TypeError:.....
2.在python中,允许多个变量指向同一个值,并且修改一个变量不影响另一个变量(其实和C++一样),例如:
>>>x=3
>>>id(x)
1786684560
>>>y=x
>>>id(y)
1786684560
>>>x+=6
>>>id(x)
1786684752
>>>y
3
>>>id(y)
1786684560
3.变量名区分大小写
4.真除法:x/y;求整商:x//y
第2章、Python序列
2.0
- Python中常用的序列结构有列表、元组、字典、字符串、集合等;
- 除字典和集合属于无序序列之外,列表、元组、字符串等序列均支持双向索引,第一个元素下标为0,依次类推;
2.1列表
2.1.1列表的创建与删除
>>> a_list=[1,'a','abc',2.3]
>>> b_list=list((1,2,3,4,5))
>>> a_list
[1, 'a', 'abc', 2.3]
>>> b_list
[1, 2, 3, 4, 5]
>>> c_list=list('hello world')
>>> c_list
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
>>> del a_list[1]
>>> a_list
[1, 'abc', 2.3]
2.1.2列表元素的增加
#append属于原地增加,速度快;+属于重新创建列表(内存地址变了),速度慢
>>> alist=[3,4,5]
>>> alist=alist+[7]
>>> alist.append(9)
>>> alist
[3, 4, 5, 7, 9]
>>> alist[1]=['a']
>>> alist
[3, ['a'], 5, 7, 9]
>>> alist[1]='a'
>>> alist
[3, 'a', 5, 7, 9]
>>> alist.extend([7,8,9])
>>> alist
[3, 'a', 5, 7, 9, 7, 8, 9]
>>> alist.insert(3,6)
>>> alist
[3, 'a', 5, 6, 7, 9, 7, 8, 9]
2.1.3列表元素的删除
>>> alist=[1,2,3,4,5,6]
>>> del alist[0]
>>> alist
[2, 3, 4, 5, 6]
>>> alist.pop()
6
>>> alist
[2, 3, 4, 5]
>>> alist.pop(1)
3
>>> alist
[2, 4, 5]
>>> alist.remove(4)
>>> alist
[2, 5]
2.1.4列表元素的访问与计数
>>> alist=[3,4,5,6,7,8,9,11,12,13,14,15]
>>> alist[3]
6
>>> alist.index(7)
4
>>> alist.count(8)
1
2.1.5切片操作
切片使用2个冒号分隔的3个数字完成:第一个数字表示切片开始位置(默认0),第二个数字表示切片截止(但不包含)位置(默认为列表长度),第三个数字表示切片的步长(默认1),当步长省略时可以顺便省略最后一个冒号。切片操作也适用于列表、元组、字符串、range对象。
可以通过切片来修改、删除和增加列表的部分元素。
访问列表元素:
>>> alist=[3,4,5,6,7,8,9,11,13,15,17]
>>> alist[::]
[3, 4, 5, 6, 7, 8, 9, 11, 13, 15, 17]
>>> alist[::-1]
[17, 15, 13, 11, 9, 8, 7, 6, 5, 4, 3]
>>> alist[::2]
[3, 5, 7, 9, 13, 17]
>>> alist[1::2]
[4, 6, 8, 11, 15]
>>> alist[3::]
[6, 7, 8, 9, 11, 13, 15, 17]
>>> alist[:4]
[3, 4, 5, 6]
>>> alist[0:100]
[3, 4, 5, 6, 7, 8, 9, 11, 13, 15, 17]
>>> alist[100]
Traceback (most recent call last):
File "<pyshell#124>", line 1, in <module>
alist[100]
IndexError: list index out of range
>>> alist[100:]
[]
原地修改列表元素:
>>> alist=[3,5,7]
>>> alist[len(alist):]
[]
>>> alist[len(alist):]=[9,11]
>>> alist
[3, 5, 7, 9, 11]
>>> alist[:3]=[1,2,3]
>>> alist
[1, 2, 3, 9, 11]
>>> del alist[:3]
>>> alist
[9, 11]
切片返回的是列表元素的浅复制
2.1.6列表排序
#原地升降序
>>> alist=[3,4,5,6,7,8,9,11,13,15,17]
>>> import random
>>> random.shuffle(alist)
>>> alist
[3, 11, 8, 13, 9, 7, 6, 4, 5, 15, 17]
>>> alist.sort()
>>> alist
[3, 4, 5, 6, 7, 8, 9, 11, 13, 15, 17]
>>> alist.sort(reverse=True)
>>> alist
[17, 15, 13, 11, 9, 8, 7, 6, 5, 4, 3]
2.2元组
元组属于不可变序列,元组一旦创建,用任何方法都不可以修改其元素的值,也无法为元组增加和删除元素。
2.2.1元组的创建和删除
>>> a_tuple=('a','abc',1,2,3)
>>> a_tuple
('a', 'abc', 1, 2, 3)
>>> a_tuple=(3,)
>>> a_tuple
(3,)
>>> a_tuple=(3)
>>> a_tuple
3
>>> a_tuple=3,
>>> a_tuple
(3,)
>>> a_tuple=1,2
>>> a_tuple
(1, 2)
>>> a_tuple=tuple([1,2,3,4,5])
>>> a_tuple
(1, 2, 3, 4, 5)
>>> del a_tuple[1]
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
del a_tuple[1]
TypeError: 'tuple' object doesn't support item deletion
>>> a_tuple
(1, 2, 3, 4, 5)
>>> del a_tuple
>>> a_tuple
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
a_tuple
NameError: name 'a_tuple' is not defined
2.2.2元组和列表的区别
- 列表属于可变序列,可以随意地修改列表中的元素值以及增加和删除列表元素,而元组属于不可变序列,元组中的数据一旦定义就不允许通过任何方式更改;
- 元组和列表都是有序序列,可以通过下表方式访问内部元素,也可通过切片的方式访问元组元素(元组只能访问);
虽然元组是不可变序列,但如果元组中包含可变序列元素,情况就略有不同:
>>> x=([1,2],3)
>>> x[0][0]
1
>>> x[0][0]=5
>>> x
([5, 2], 3)
>>> x[0].append(8)
>>> x
([5, 2, 8], 3)
>>> x[0]=x[0]+[10]
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
x[0]=x[0]+[10]
TypeError: 'tuple' object does not support item assignment
>>> x
([5, 2, 8], 3)
2.2.3序列解包
>>> a=[1,2,3]
>>> b,c,d=a
>>> print(b,c,d)
1 2 3
>>> s={'a':1,'b':2,'c':3}
>>> b,c,d=s.items()
>>> b
('b', 2)
>>> print(b,c,d)
('b', 2) ('a', 1) ('c', 3)
>>> b,c,d=s
>>> print(b,c,d)
b a c
>>> b,c,d=s.values()
>>> print(b,c,d)
2 1 3
>>>
>>>
>>>
>>> keys=['a','b','c','d']
>>> values=[1,2,3,4]
>>> for k,v in zip(keys,values):
print(k,v)
a 1
b 2
c 3
d 4
2.2.4生成器推导式
>>> g=((i+2)**2 for i in range(10))
>>> g
<generator object <genexpr> at 0x000001D6B6A562B0>
>>> tuple(g)
(4, 9, 16, 25, 36, 49, 64, 81, 100, 121)
>>> tuple(g)
()
>>> g=((i+2)**2 for i in range(10))
>>> list(g)
[4, 9, 16, 25, 36, 49, 64, 81, 100, 121]
>>> g=((i+2)**2 for i in range(10))
>>> g.next()
Traceback (most recent call last):
File "<pyshell#76>", line 1, in <module>
g.next()
AttributeError: 'generator' object has no attribute 'next'
>>> g.__next__()
4
>>> g.__next__()
9
>>> g=((i+2)**2 for i in range(10))
>>> for i in g:
print i;
SyntaxError: Missing parentheses in call to 'print'
>>> for i in g:
print i,
SyntaxError: Missing parentheses in call to 'print'
>>> for i in g:
print (i,end='')
49162536496481100121
>>> g=((i+2)**2 for i in range(10))
>>> for i in g:
print(i,end=' ')
4 9 16 25 36 49 64 81 100 121
>>> for i in g:
print(i,end=' ')
>>>
2.3字典
- 字典是“键-值对”的无序可变序列,字典中的每个元素包含两部分:“键”和“值”;
- 字典中的“键”可以是Python中任意不可变数据,例如整数、实数、复数、字符串、元组等,但不能使用列表、集合、字典作为字典的
“键”,因为这些对象是可变的; - “键”不允许重复,“值”可以重复;
- 内置函数globals()返回和查看包含当前作用域内所有全局变量和值的字典,内置函数locals()返回包含当前作用域内所有局部变量和值的字典;
>>> a=(1,2,3,4,5)
>>> b='hello world'
>>> def demo():
a=3
b=[1,2,3]
print('locals:',locals())
print('globals:',globals())
>>> demo()
locals: {'b': [1, 2, 3], 'a': 3}
globals: {'__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, 'demo': <function demo at 0x000002248A1000D0>, 'a': (1, 2, 3, 4, 5), '__loader__': <class '_frozen_importlib.BuiltinImporter'>, 'b': 'hello world', '__doc__': None, '__package__': None, '__spec__': None}
>>>
2.3.1字典创建与删除
>>> a_dict={'a':1,'b':2,'c':3}
>>> a_dict
{'c': 3, 'b': 2, 'a': 1}
>>> keys=['aa','bb','cc']
>>> values=[1,2,2]
>>> dictionary=dict(zip(keys,values))
>>> print(dictionary)
{'bb': 2, 'cc': 2, 'aa': 1}
>>> d=dict(name='hm',age=23)
>>> d
{'name': 'hm', 'age': 23}
>>>
>>> adict=dict.fromkeys(['name','age'])
>>> adict
{'name': None, 'age': None}
>>> del adict
>>> adict
Traceback (most recent call last):
File "<pyshell#130>", line 1, in <module>
adict
NameError: name 'adict' is not defined
>>>
2.3.2字典元素的读取
>>> adict={'name':'hm','sex':'male','age':23}
>>> adict['name']
'hm'
>>> print(adict.get('age'))
23
>>> for item in adict.items():
print(item)
('name', 'hm')
('age', 23)
('sex', 'male')
>>> for key in adict:
print(key)
name
age
sex
>>> for key,value in adict.items():
print(key,value)
name hm
age 23
sex male
>>>
2.3.3字典元素的添加和修改
>>> adict['age']=30
>>> adict
{'name': 'hm', 'age': 30, 'sex': 'male'}
>>> adict['address']='njust'
>>> adict
{'name': 'hm', 'age': 30, 'sex': 'male', 'address': 'njust'}
>>> adict.update({'a':'a','address':'nj'})
>>> adict
{'name': 'hm', 'age': 30, 'a': 'a', 'sex': 'male', 'address': 'nj'}
>>>
2.4集合
- 集合是无序可变序列;
- 集合中的元素必须唯一,不能重复
2.4.1集合的创建与删除
>>> a={3,5}
>>> a.add(7)
>>> a
{3, 5, 7}
>>> a_set=set(range(8,14))
>>> a_set
{8, 9, 10, 11, 12, 13}
>>> b_set=set({1,1,2,2,3,3,4,4,5,5,})
>>> b_set
{1, 2, 3, 4, 5}
>>> b_set.pop()
1
>>> b_set
{2, 3, 4, 5}
>>> b_set.remove(4)
>>> b_set
{2, 3, 5}
>>> b_set.clear()
>>> b_set
set()
>>>
2.4.2集合操作
>>> a_set=set([8,9,10,11,12,13])
>>> b_set=set({0,1,2,3,7,8})
>>> a_set|b_set
{0, 1, 2, 3, 7, 8, 9, 10, 11, 12, 13}
>>> a_set.union(b_set)
{0, 1, 2, 3, 7, 8, 9, 10, 11, 12, 13}
>>> a_set&b_set
{8}
>>> a_set.intersection(b_set)
{8}
>>> a_set.difference(b_set)
{9, 10, 11, 12, 13}
>>>
第3章、选择与循环
3.1条件表达式
判断条件和C语言相似,不为空返回True,为空返回False
3.2选择结构
3.2.1单分支选择结构
>>> x=input('input two numbers:')
input two numbers:5 3
>>> a,b=map(int,x.split())
>>> if a>b:
a,b=b,a
>>> print(a,b)
3 5
>>>
3.2.2双分支选择结构
>>> chTest=['1','2','3']
>>> if chTest:
print(chTest)
else:
print('Empty')
['1', '2', '3']
>>>
>>> a=5
>>> print(6) if a>3 else print(5)
6
>>>
3.2.3多分支选择结构
>>> def func(score):
if score>100:
return 'wrong score.must<=100'
elif score>=90:
return 'A'
elif score>=80:
return 'B'
elif score>=70:
return 'C'
elif score>=0:
return 'D'
else:
return 'wrong score.must>=0'
>>> func(120)
'wrong score.must<=100'
>>> func(88)
'B'
>>>
3.2.4选择结构案例:编写程序判断某天是某年的第几天
import time
def demo(year,month,day):
day_month=[31,28,31,30,31,30,31,31,30,31,30,31]
if year%400==0 or (year%4==0 and year%100!=0):
day_month[1]=29
if month==1:
return day
else:
return sum(day_month[:month-1])+day
date=time.localtime()
year,month,day=date[:3]
print(demo(year,month,day))
3.3循环结构
- for循环与while循环
- 应尽量减少内层循环中不必要的计算,尽可能的向外提
- 在循环中应尽量引用局部表量
import time
digits=(1,2,3,4)
start=time.time()
for i in range(1000):
result=[]
for i in digits:
i=i*100
for j in digits:
j*=10
for k in digits:
result.append(i+j+k)
print(time.time()-start)
print(result)
3.4break和continue语句
类似C语言中break和continue