nonlocal关键字
>>> def fun1():
def fun2():
x*=x
return x
>>> fun1()
5
>>> def fun1():
x=5
def fun2():
x*=x
return x
return fun2()
>>> fun1()
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
fun1()
File "<pyshell#34>", line 6, in fun1
return fun2()
File "<pyshell#34>", line 4, in fun2
x*=x
UnboundLocalError: local variable 'x' referenced before assignment
>>> def fun1()
SyntaxError: invalid syntax
>>> def fun1():
x=5
def fun2():
nonlocal x(这里用这个关键字说明要将x强制成一个局部变量)
x*=x
return x
return fun2()
>>> fun1()
25
内嵌函数
>>> def fun1():
x=5
def fun2():
x*=x
return x
>>> fun1()
5
>>> fun2()
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
fun2()
NameError: name 'fun2' is not defined
filter()过滤器
要过滤掉1-10中的偶数
>>> list(filter(lambda x:x%2,range(10)))
[1, 3, 5, 7, 9]
lambda关键字构建匿名函数,有时候可以省去了起名的繁琐
>>> lambda x:x*x+1
<function <lambda> at 0x000001650BE6E268>
>>> g=lambda x:x*x+1
>>> g(5)
26
斐波那契数列的python实现:
def feibonaqi(n: object) -> object:
if(n==1):
return 1
elif(n==2):
return 1
elif(n>2):
return feibonaqi(n-1)+feibonaqi(n-2)
number=int(input("请输入一个数"))
r=feibonaqi(number)
print(r)
n=1与n=2时结果一样的,就想着用个或,不过python中没有&&和||,有&和|,不过出错了。。。这是为什么
递归-汉诺塔(其实非常简单,想明白就好)
def hanoi(n,x,y,z):
if n==1:
print(x,'-->',z)
else:
hanoi(n-1,x,z,y)#将前n-1个盘子从x移动到y
print(x,'-->',z)#将第n个盘子从x移动到z上
hanoi(n-1,y,x,z)#将y上的n-1个盘子移动到z上
n=int(input("请输入层数"))
hanoi(n,'X','Y','Z')
字典(标志性就是大括号,对应的键和多个值构成)底下有dict详解
>>> dict1={'李宁':'xixi','耐克':'xixi1'}
>>> print('李宁的口号是:',dict1['李宁'])
李宁的口号是: xixi
>>> dict2={1:'one',2:'two',3:'three'}
>>> dict2
{1: 'one', 2: 'two', 3: 'three'}
>>> dict2[2]
'two'
>>> dict3={}
>>> dict3
{}
>>> dict4=dict(小甲鱼='xixi',哈哈='lala')
>>> dict4
{'小甲鱼': 'xixi', '哈哈': 'lala'}
>>> print('小甲鱼的口号是:',dict4['小甲鱼'])
小甲鱼的口号是: xixi
>>> dict4['苍井空']='所有AV从业者xixixi'
>>> dict4
{'小甲鱼': 'xixi', '哈哈': 'lala', '苍井空': '所有AV从业者xixixi'}
>>> dict4['爱迪生']='xixi'
>>> dict4
{'小甲鱼': 'xixi', '哈哈': 'lala', '苍井空': '所有AV从业者xixixi', '爱迪生': 'xixi'}
>>> help(dict)
Help on dict object:
class dict(object)
| dict() -> new empty dictionary
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs
| dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
| in the keyword argument list. For example: dict(one=1, two=2)
|
| Methods defined here:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(...)
| x.__getitem__(y) <==> x[y]
|
| __gt__(self, value, /)
| Return self>value.
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| __setitem__(self, key, value, /)
| Set self[key] to value.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
| If key is not found, d is returned if given, otherwise KeyError is raised
|
| popitem(...)
| D.popitem() -> (k, v), remove and return some (key, value) pair as a
| 2-tuple; but raise KeyError if D is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| fromkeys(iterable, value=None, /) from builtins.type
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
fromkeys关键字
>>> 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=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
in 和not in(返回True以及False)
clear,之前已经使b=a,如果直接重新构建a的空数组,b还是保留了a的内容,没办法清空,如果用clear,则b中的内容也会同时被清空
>>> a={'姓名':'xixi'}
>>> b=a
>>> b
{'姓名': 'xixi'}
>>> a={}
>>> a
{}
>>> b
{'姓名': 'xixi'}
>>> a.clear()
>>> a
{}
>>> b
{'姓名': 'xixi'}
>>> b=a
>>> b
{}
浅拷贝copy()和直接赋值(注意浅拷贝的id是有变化的,直接赋值(贴了一个不同的标签在相同的数据上)id是没有变化的),后面加了个four,a被干扰了,b没变
>>> a={1:'one',2:'two'}
>>> b=a.copy()
>>> c=a
>>> c
{1: 'one', 2: 'two'}
>>> b
{1: 'one', 2: 'two'}
>>> a
{1: 'one', 2: 'two'}
>>> id(a)
1898952360944
>>> id(b)
1898952360872
>>> id(c)
1898952360944
>>> c[4]='four'
>>> a
{1: 'one', 2: 'two', 4: 'four'}
>>> b
{1: 'one', 2: 'two'}
去除列表中重复的元素(如果没有set,则就用前几行代码来解决,有set就方便很多了)
>>> num1=[1,2,3,4,5,5,3,1,0]
>>> temp=[]
>>> for each in num1:
if each not in temp:
temp.append(each)
>>> temp
[1, 2, 3, 4, 5, 0]
>>> num1=list(set(num1))
>>> num1
[0, 1, 2, 3, 4, 5]
frozenset就会冰冻集合,就不能再对此集合进行操作了(如果增加元素就会报错)
>>> num3=frozenset([1,2,3,4])
>>> num3.append('xixi')
Traceback (most recent call last):
File "<pyshell#68>", line 1, in <module>
num3.append('xixi')
AttributeError: 'frozenset' object has no attribute 'append'