python 列表转为字典的两个小方法
1、现在有两个列表,list1 = ['key1','key2','key3']和list2 = ['1','2','3'],把他们转为这样的字典:{'key1':'1','key2':'2','key3':'3'}
list1 = ['key1','key2','key3']
list2 = ['1','2','3']
dict(zip(list1,list2))
{'key1':'1','key2':'2','key3':'3'}
2、将嵌套列表转为字典,有两种方法,
new_list= [['key1','value1'],['key2','value2'],['key3','value3']]
dict(list)
{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}
python for else 陷阱
for i in range(10):
if i == 5:
print('hello %s' % i)
else:
print('word ...')
hello 5
word ...
for i in range(10):
if i == 5:
print('hello %s' % i)
break
else:
print('word ...')
hello 5
#当迭代的对象迭代完并为空时,位于else的子句将执行,而如果在for循环中含有break时则直接终止循环,并#不会执行else子句。
python 反转列表
a=[1,2,3,4,5,6,7,8,9]
d=a[::-1]
print(d)
[9, 8, 7, 6, 5, 4, 3, 2, 1]
li =[1, 2, 3, 4, 5, 6]
a = list(reversed(li))
print (a)
[6, 5, 4, 3, 2, 1]
python3 继承 在子类中如何调用父类中的方法
'''
继承
'''
class A:
# a = 1
def func(self):
self.a = 8
print('123')
def func3(self):
self.a = 0
return self.a
class B(A):
b = 2
def func2(self):
'''
两种在子类调用父类函数的方法,
一、使用未绑定子类的父类的方法,要传入子类的对象,即self A.func(self)
二、使用super()调用 super().func()
'''
A.func(self)
#super().func()
print('qwe')
b = B()
b.func2()
python 异常捕获中的return
def something():
try:
return 'hello'
except Exception as e:
print(e)
finally:
return 'world'
print(something())
world
def something():
try:
return 'hello'
except Exception as e:
print(e)
finally:
print('world')
print(something())
world
hello