016 序列序列!
>>> a = list()
>>> a
[]
>>> b = "I love fishC.com!"
>>> b = list(b)
>>> b
['I', ' ', 'l', 'o', 'v', 'e', ' ', 'f', 'i', 's', 'h', 'C', '.', 'c', 'o', 'm', '!']
>>> c = [1, 1, 2, 3, 8, 13, 21, 34]
>>> c = list(c)
>>> c
[1, 1, 2, 3, 8, 13, 21, 34]
>>> len(a)
0
>>> len(b)
17
>>> max(1,2,34,5)
34
>>> max(b)
'v'
>>> numbers = [1, 18, 13, 0, 34, 54, 76, 12]
>>> numbers
[1, 18, 13, 0, 34, 54, 76, 12]
>>> max(numbers)
76
>>> min(numbers)
0
>>> chars = '1234567890'
>>> min(chars)
'0'
>>> tuple1 = (1,2,3,4,5,6,7,8,9,0)
>>> max(tuple1)
9
>>> numbers.append('a')
>>> numbers
[1, 18, 13, 0, 34, 54, 76, 12, 'a']
>>> #sum(iterable[,start = 0])
>>> tuple2 = (3.1, 2.3, 3.4)
>>> sum(tuple2)
8.8
>>> numbers.pop()
'a'
>>> numbers
[1, 18, 13, 0, 34, 54, 76, 12]
>>> sum(numbers)
208
>>> sum(numbers,8)
216
>>> chars
'1234567890'
>>> sorted(numbers)
[0, 1, 12, 13, 18, 34, 54, 76]
>>> reversed(numbers)
<list_reverseiterator object at 0x0219FFF0>
>>> list(reversed(numbers))
[12, 76, 54, 34, 0, 13, 18, 1]
>>> enumerate(numbers)
<enumerate object at 0x021BE1E8>
>>> list(enumerate(numbers))
[(0, 1), (1, 18), (2, 13), (3, 0), (4, 34), (5, 54), (6, 76), (7, 12)]
>>> a = [1,2,3,4,5,6,7,8]
>>> b = [4,5,6,7,8]
>>> zip(a,b)
<zip object at 0x021BE210>
>>> list(zip(a,b))
[(1, 4), (2, 5), (3, 6), (4, 7), (5, 8)]
017 函数:Python的乐高积木
>>> def MyFirstFunction():
print("这是创建的第一个函数!")
print("我表示很激动。。。。")
print("在此,我将感谢TVB,感谢VVAV,感谢小甲鱼,感谢大家")
>>> #函数后面要有小括号
>>> MyFirstFunction()
这是创建的第一个函数!
我表示很激动。。。。
在此,我将感谢TVB,感谢VVAV,感谢小甲鱼,感谢大家
>>> def MySecondfuncton(name):
print(name + '啦啦')
>>> MySecondfuncton('笨笨')
笨笨啦啦
>>> def aaa(name1, name2):
result = name1 + name2
print(result)
>>> aaa(1,5)
6
>>> #函数的返回值
>>> def aaa(name1, name2):
return(name1 + name2)
>>> print(aaa(1,5))
6
018 函数:灵活强大
>>> #形参:name,实参:笨笨
>>> def MyFirstFunction1(name):
'函数定义过程中的name是形参'
#因为ta只是一个形式,表示占据一个参数位置
print('传递进来的' + name + '叫做实参,因为ta是具体的参数值!')
>>> MyFirstFunction1('小甲鱼')
传递进来的小甲鱼叫做实参,因为ta是具体的参数值!
>>> MyFirstFunction1.__doc__
'函数定义过程中的name是形参'
>>> help(MyFirstFunction1)
Help on function MyFirstFunction1 in module __main__:
MyFirstFunction1(name)
函数定义过程中的name是形参
>>> print.__doc__
"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\nPrints the values to a stream, or to sys.stdout by default.\nOptional keyword arguments:\nfile: a file-like object (stream); defaults to the current sys.stdout.\nsep: string inserted between values, default a space.\nend: string appended after the last value, default a newline.\nflush: whether to forcibly flush the stream."
>>> help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
>>> def SaySome(name, words):
print(name + '->' + words)
>>> SaySome('笨笨', '啦啦啦')
笨笨->啦啦啦
>>> SaySome(words = '啦啦啦', name = '笨笨')
笨笨->啦啦啦
>>> #默认参数
>>> def SaySome(name = '小甲鱼', words = 'lalala'):
print(name + '->' + words)
>>> SaySome()
小甲鱼->lalala
>>> SaySome('笨笨')
笨笨->lalala
>>> SaySome('笨笨', '唱首歌吧')
笨笨->唱首歌吧
>>> #收集参数
>>> def test(*paras):
print('参数的长度: ', len(paras));
print('第二个参数是:',paras[1]);
>>> test(1, '小甲鱼', 3.14, 5, 6, 7, 8)
参数的长度: 7
第二个参数是: 小甲鱼
>>> def test(*paras, exp):
print('参数的长度: ', len(paras), exp);
print('第二个参数是:',paras[1]);
>>> test(1, '小甲鱼', 3.14, 5, 6, 7, exp = 8)
参数的长度: 6 8
第二个参数是: 小甲鱼
019 函数与过程
>>> def hello():
print('hello fishC')
>>> temp = hello()
hello fishC
>>> temp
>>> print(temp)
None
>>> type(temp)
<class 'NoneType'>
def discounts(price, rate):
final_price = price * rate
old_price = 88 #这里试图修改全局变量
print('修改old_price的值是:', old_price)
return final_price
old_price = float(input('请输入原价:'))
rate = float(input('请输入折扣率:'))
new_price = discounts(old_price, rate)
print('修改后old_price的值是:', old_price)
print('打折后价格是:', new_price)
#在函数里面定义的参数为局部变量
#print('打折后价格是:', new_price),不可打印final_price,new_price在函数外部定义,为全局变量
020 函数:内嵌函数和闭包
global关键字:在函数内部仅访问全局变量就好,不要去修改它。
>>> #内嵌函数和闭包
>>> count = 5
>>> def MyFun():
count = 10
print(10)
>>> MyFun()
10
>>> print(count)
5
>>> def MyFun():
global count
count = 10
print(10)
>>> MyFun()
10
>>> print(count)
10
>>> #内嵌函数
>>> def fun1():
print('fun1()正在被调用。。')
def fun2():
print('fun2()正在被调用。。')
fun2()
>>> fun1()
fun1()正在被调用。。
fun2()正在被调用。。
>>> #内部函数整个作用都在函数之内
>>> #闭包
>>> def funX(x):
def funY(y):
return x * y
return funY
>>> i = funX(8)
>>> i
<function funX.<locals>.funY at 0x0239E198>
>>> type(i)
<class 'function'>
>>> i(5)
40
>>> funX(8)(5)
40
>>> funY(5)
Traceback (most recent call last):
File "<pyshell#155>", line 1, in <module>
funY(5)
NameError: name 'funY' is not defined
>>> def fun1():
x = 5
def fun2():
x *= x
return x
return fun2
>>> fun1()
<function fun1.<locals>.fun2 at 0x01732858>
>>> def fun1():
x = 5
def fun2():
x *= x
return x
return fun2()
>>> fun1()
Traceback (most recent call last):
File "<pyshell#166>", line 1, in <module>
fun1()
File "<pyshell#165>", line 6, in fun1
return fun2()
File "<pyshell#165>", line 4, in fun2
x *= x
UnboundLocalError: local variable 'x' referenced before assignment
>>> def fun1():
x = [5]
def fun2():
x[0] *= x[0]
return x[0]
return fun2()
>>> fun1()
25
>>> def fun1():
x = 5
def fun2():
nonlocal x
x *= x
return x
return fun2()
>>> fun1()
25
021 函数:lambda表达式
>>> def ds(x):
return 2*x+1
>>> ds(5)
11
>>> lambda x : 2*x+1
<function <lambda> at 0x023B3030>
>>> g = lambda x : 2*x+1
>>> g(5)
11
>>> def add(x, y):
return x + y
>>> add(3, 4)
7
>>> lambda x, y : x + y
<function <lambda> at 0x023B30C0>
>>> g = lambda x, y : x + y
>>> g(3, 4)
7
>>> #filter()函数
>>> help(filter)
Help on class filter in module builtins:
class filter(object)
| filter(function or None, iterable) --> filter object
|
| Return an iterator yielding those items of iterable for which function(item)
| is true. If function is None, return the items that are true.
|
| Methods defined here:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)
| Return state information for pickling.
>>> filter(None, [1, 0, False, True])
<filter object at 0x0219F3D0>
>>> list(filter(None, [1, 0, False, True]))
[1, True]
>>> def odd(x):
return x % 2
>>> temp = range(10)
>>> show = filter(odd, temp)
>>> list(show)
[1, 3, 5, 7, 9]
>>>
>>> list(filter(lambda x : x % 2, range(10)))
[1, 3, 5, 7, 9]
>>> #map()
>>> list(map(lambda x : x * 2,range(10)))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
022 函数:递归是神马
def factorial(n):
result = n
for i in range(1,n):
result *= i
return result
number = int(input('请输入一个正整数:'))
result = factorial(number)
print("%d 的阶乘是:%d" % (number, result))
#递归
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
number = int(input('请输入一个正整数:'))
result = factorial(number)
print('%d 的阶乘是:%d' % (number, result))
023 递归:这帮小兔崽子
迭代法
def fab(n):
n1 = 1
n2 = 1
n3 = 1
if n < 1:
print('输入有误!')
return -1
while (n - 2) > 0:
n3 =n2 + n1
n1 = n2
n2 = n3
n -= 1
return n3
result = fab(20)
if result != -1:
print('总共有%d只小兔子诞生!' % result)
递归法
def fab(n):
if n < 1:
print('输入有误!')
return -1
if n == 1 or n == 2:
return 1
else:
return fab(n-1) + fab(n-2)
result = fab(20)
if result != -1:
print('共有%d只小兔子' % result)
#分治思想
迭代比递归效率高
024 递归:汉诺塔
def hanol(n, x, y, z):
if n == 1:
print(x, '-->', z)
else:
hanol(n-1, x, z, y)#将前n-1个盘子从x移动到y上
print(x, '-->', z)#将最底下的最后一个盘子从x移动到z上
#将y上的n-1个盘子移动到z上
hanol(n-1, y, x, z)
n = int(input('请输入汉诺塔的层数:'))
hanol(n, 'x', 'y', 'z')
请输入汉诺塔的层数:4
x --> y
x --> z
y --> z
x --> y
z --> x
z --> y
x --> y
x --> z
y --> z
y --> x
z --> x
y --> z
x --> y
x --> z
y --> z
025 字典:当索引不好用时
创建和访问字典
>>> brand = ['李宁', '耐克', '阿迪达斯', 'fishC']
>>> slogan = ['一切皆有可能', 'just do it', 'Impossile is nothing', '让编程改变世界']
>>> print('鱼C工作室的口号是:', slogan[brand.index('fishC')])
鱼C工作室的口号是: 让编程改变世界
>>> dict1 = {'李宁', '耐克', '阿迪达斯', 'fishC'}
>>> dict1 = {'李宁':'一切皆有可能', '耐克':'just do it', '阿迪达斯':'Impossile is nothing', 'fishC':'让编程改变世界'}
>>> print('鱼C工作室的口号是:', dict1['fishC'])
鱼C工作室的口号是: 让编程改变世界
>>> dict2 = {1:'one',2:'two',3:'three'}
>>> dict2
{1: 'one', 2: 'two', 3: 'three'}
>>> dict2[2]
'two'
>>>
>>> dict3 = {}
>>> dict3
{}
>>> dict3 = dict((('F',70), ('i',105),('h',104),('c',76)))
>>> dict3
{'F': 70, 'i': 105, 'h': 104, 'c': 76}
>>> dict4 = dict(小甲鱼 = '让编程改变世界', 苍井空 = '让AV征服所有宅男')
>>> dict4
{'小甲鱼': '让编程改变世界', '苍井空': '让AV征服所有宅男'}
>>> dict4['苍井空'] = '所有AV从业者都要通过学习编程来提高职业技能'
>>> dict4
{'小甲鱼': '让编程改变世界', '苍井空': '所有AV从业者都要通过学习编程来提高职业技能'}
>>> dict4['爱迪生'] = '天才是99%的汗水+1%的灵感,但这1%的灵感远比汗水更重要'
>>> dict4
{'小甲鱼': '让编程改变世界', '苍井空': '所有AV从业者都要通过学习编程来提高职业技能', '爱迪生': '天才是99%的汗水+1%的灵感,但这1%的灵感远比汗水更重要'}
>>>
026 字典:当索引不好用时2
>>> dict1 = {}
>>> dict1.fromkeys((1,2,3))
{1: None, 2: None, 3: None}
>>> dict1.fromkeys((1,2,3),'Number')
{1: 'Number', 2: 'Number', 3: 'Number'}
>>> dict1.fromkeys((1,2,3),('one','two','three'))
{1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')}
>>> dict1.fromkeys ((1,3),'数字')
{1: '数字', 3: '数字'}
>>> #keys(),values().items()
>>> dict1 = dict1.fromkeys(range(32),'赞')
>>> dict1
{0: '赞', 1: '赞', 2: '赞', 3: '赞', 4: '赞', 5: '赞', 6: '赞', 7: '赞', 8: '赞', 9: '赞', 10: '赞', 11: '赞', 12: '赞', 13: '赞', 14: '赞', 15: '赞',
16: '赞', 17: '赞', 18: '赞', 19: '赞', 20: '赞', 21: '赞', 22: '赞', 23: '赞', 24: '赞', 25: '赞', 26: '赞', 27: '赞', 28: '赞', 29: '赞', 30: '赞',
31: '赞'}
>>> for eachKey in dict1.keys():
print(eachKey)
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
>>> for eachKey in dict1.values():
print(eachKey)
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
>>> for eachKey in dict1.items():
print(eachKey)
(0, '赞')
(1, '赞')
(2, '赞')
(3, '赞')
(4, '赞')
(5, '赞')
(6, '赞')
(7, '赞')
(8, '赞')
(9, '赞')
(10, '赞')
(11, '赞')
(12, '赞')
(13, '赞')
(14, '赞')
(15, '赞')
(16, '赞')
(17, '赞')
(18, '赞')
(19, '赞')
(20, '赞')
(21, '赞')
(22, '赞')
(23, '赞')
(24, '赞')
(25, '赞')
(26, '赞')
(27, '赞')
(28, '赞')
(29, '赞')
(30, '赞')
(31, '赞')
>>> print(dict1[31])
赞
>>> dict1.get(32)
>>> print(dict1.get(32))
None
>>> dict1.get(32,'木有!')
'木有!'
>>> #检查字典元素是否在里面 in ;not in
>>> 32 in dict1
False
>>> 31 in dict1
True
>>> dict1
{0: '赞', 1: '赞', 2: '赞', 3: '赞', 4: '赞', 5: '赞', 6: '赞', 7: '赞', 8: '赞', 9: '赞', 10: '赞', 11: '赞', 12: '赞', 13: '赞', 14: '赞', 15: '赞', 16: '赞', 17: '赞', 18: '赞', 19: '赞', 20: '赞', 21: '赞', 22: '赞', 23: '赞', 24: '赞', 25: '赞', 26: '赞', 27: '赞', 28: '赞', 29: '赞', 30: '赞', 31: '赞'}
>>> dict1.clear()
>>> dict1
{}
>>> dict1 = {}
>>> a = {1:'one',2:'two',3:'three'}
>>> b = a.copy()
>>> c = a
>>> c
{1: 'one', 2: 'two', 3: 'three'}
>>> b
{1: 'one', 2: 'two', 3: 'three'}
>>> id(a)
35294736
>>> id(b)
35294688
>>> id(c)
35294736
>>> c[4] = 'four'
>>> c
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> a
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> b
{1: 'one', 2: 'two', 3: 'three'}
>>> a.pop(2)
'two'
>>> a
{1: 'one', 3: 'three', 4: 'four'}
>>> a.popitem()
(4, 'four')
>>> a.setdefault ('小白')
>>> a
{1: 'one', 3: 'three', '小白': None}
>>> a.setdefault(5,'five')
'five'
>>> a
{1: 'one', 3: 'three', '小白': None, 5: 'five'}
>>> b = {'小白':'汪汪'}
>>> b.update ()
>>> b
{'小白': '汪汪'}
>>> a.update (b)
>>> a
{1: 'one', 3: 'three', '小白': '汪汪', 5: 'five'}
027 集合:在我的世界里,你就是唯一!
>>> #创建集合1、花括号2、set()
>>> set1 = set([1,2,3,4,5,5])
>>> set1
{1, 2, 3, 4, 5}
>>> set2 = set([0,1,2,3,4,5,5,4,3,2,1,1])
>>> set2
{0, 1, 2, 3, 4, 5}
>>> set2 = list(set2)
>>> set2
[0, 1, 2, 3, 4, 5]
>>> #如何访问集合中的值:1、for 2、判断是否在集合中
>>> 1 in set1
True
>>> '1' in set2
False
>>> set2.add(0)
Traceback (most recent call last):
File "<pyshell#310>", line 1, in <module>
set2.add(0)
AttributeError: 'list' object has no attribute 'add'
>>> set2 = set([0,1,2,3,4,5,5,4,3,2,1,1])
>>> set2.add(6)
>>> set2
{0, 1, 2, 3, 4, 5, 6}
>>> #不可变集合
>>> num3 = frozenset([1,2,3,4,5])
>>> num3
frozenset({1, 2, 3, 4, 5})
>>> num3.add(6)
Traceback (most recent call last):
File "<pyshell#317>", line 1, in <module>
num3.add(6)
AttributeError: 'frozenset' object has no attribute 'add'