Python面经库
sogrey / python-qa Goto Github PK
View Code? Open in Web Editor NEWPython面经库
Home Page: http://sogrey.github.io/Python-QA/
License: MIT License
Python面经库
Home Page: http://sogrey.github.io/Python-QA/
License: MIT License
连接列表有两种方式:+
和extend
,元组只有一种:+
,由于元祖本身是只读的,没有extend
方法
a = [1,5,7,9,6]
b = [2,3,3,6,8]
c = (1,2,3)
d = (2,3,3,4)
print(a + b) ## [1, 5, 7, 9, 6, 2, 3, 3, 6, 8]
print(c + d) ## (1, 2, 3, 2, 3, 3, 4)
a.extend(b)
print(a) ## [1, 5, 7, 9, 6, 2, 3, 3, 6, 8]
差异:
+
不会改变参与连接的列表的值,但extend
方法可以改变a列表的值+
两侧要么都是元组,要么都是列表。但是列表的extend
方法可以将一个元组添加列表后面a.extend(c)
print(a) ## [1, 5, 7, 9, 6, 2, 3, 3, 6, 8, 1, 2, 3]
#print(a + c) ## TypeError: can only concatenate list (not "tuple") to list
print(c + d) ## (1, 2, 3, 2, 3, 3, 4)
d = {'a':123,'b':'456','c':'xyz'}
print(d) ## {'a': 123, 'b': '456', 'c': 'xyz'}
print(type(d)) ## <class 'dict'>
import json
json_str = json.dumps(d) ## json.dumps 字典->json
print(json_str) ## {"a": 123, "b": "456", "c": "xyz"}
print(type(json_str)) ## <class 'str'>
d1 = json.loads(json_str) ## json.loads json->字典
print(d1) ## {'a': 123, 'b': '456', 'c': 'xyz'}
print(type(d1)) ## <class 'dict'>
使用dumps
函数可以将字典转换为JSON字符串,使用loads
函数可以将JSON字符串转换为字典。
a = [
{'name':'Bill','age':40},
{'name':'Mike','age':12},
{'name':'Johb','age':29}
]
print(a) ## [{'name': 'Bill', 'age': 40}, {'name': 'Mike', 'age': 12}, {'name': 'Johb', 'age': 29}]
print(sorted(a,key=lambda x:x['age'])) ## [{'name': 'Mike', 'age': 12}, {'name': 'Johb', 'age': 29}, {'name': 'Bill', 'age': 40}]
a.sort(key=lambda x:x['age'],reverse=True) ## reverse=True 降序,默认false升序
print(a) ## [{'name': 'Bill', 'age': 40}, {'name': 'Johb', 'age': 29}, {'name': 'Mike', 'age': 12}]
Lambda表达式只有一行代码,并返回该行代码的结果
lambda x:x["age"] ## 对列表元素中的age属性值排序
s1 = 'abcde'
s2 = ""
for c in s1:
s2 = c + s2
print(s2) ## edcba
# 使用分片
# [a:b:c]
print(s1[::-1]) ## edcba
使用分片 #15
如何定义集合,集合与列表的区别
a = [1,2,3,4,5] # 列表
print(type(a)) ## <class 'list'>
b = (1,2,3,4,5) # 元组
print(type(b)) ## <class 'tuple'>
c = {1,2,3,4,5} # 集合
print(type(c)) ## <class 'set'>
区别:
a = [1,2,2,3,4,3]
print(a) ## [1, 2, 2, 3, 4, 3]
c = {1,2,2,3,4,3}
print(c) ## {1, 2, 3, 4}
a1 = [1,2,3]
a2 = [3,2,1]
print(a1 == a2) # False 列表与元素顺与有关
b1 = {1,2,3}
b2 = {3,2,1}
print(b1 == b2) # True 集合与元素顺与无关
通过Template对象封装 $
放置一些占位符,并通过substitute
方法用实际的值替换这些占位符
from string import Template
template1 = Template('$s是我最喜欢的编程语言,$s非常容易学习,而且功能强大')
print(template1.substitute(s = 'Python')) ## Python是我最喜欢的编程语言,Python非常容易学习,而且功能强大
print(template1.substitute(s = 'PHP')) ## PHP是我最喜欢的编程语言,PHP非常容易学习,而且功能强大
template2 = Template('${h}ello world')
print(template2.substitute(h = 'abc')) ## abcello world
template3 = Template('$dollar$$相当于多少$pounds英镑') ## $$ 转义 为输出$符
print(template3.substitute(dollar=20,pounds=16)) ## 20$相当于多少16英镑
data = {}
data['dollar'] = 30
data['pounds'] = 25
print(template3.substitute(data)) ## 30$相当于多少25英镑
模板字符串是Template类封装的一个字符串,可以用$指定占位符,
或使用字典赋值并使用substitute方法替换这些占位符
a = [i for i in range(101)]
print(a)
[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, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
同样输出0-100平方值
a = [i*i for i in range(101)]
print(a)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900,
961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401, 2500, 2601, 2704, 2809, 2916, 3025, 3136, 3249, 3364, 3481, 3600, 3721, 3844, 3969, 4096, 4225, 4356, 4489, 4624, 4761, 4900, 5041, 5184, 5329, 5476, 5625, 5776, 5929, 6084, 6241, 6400, 6561, 6724, 6889, 7056, 7225, 7396, 7569, 7744, 7921, 8100, 8281, 8464, 8649, 8836, 9025, 9216, 9409, 9604, 9801, 10000]
# [a:b:c]
print(s1[::-1]) ## edcba
排序列表的方法
a = [5,4,2,7,3,8,3]
a.sort()
print(a) # [2, 3, 3, 4, 5, 7, 8]
b = [6,4,3,3,76,2,234]
c = sorted(b)
print(c) # [2, 3, 3, 4, 6, 76, 234]
编写一个函数,用于随机排列列表中的元素
a = [1,2,3,4,5,6,7, 8, 9,0 ]
import random # 导入随机数模块
# 方案1
def random_list1(a):
for i in range(0,100):
index1 = random.randint(0, len(a) - 1)
index2 = random.randint(0, len(a) - 1)
a[index1],a[index2] = a[index2],a[index1] # 交换
return a
b = random_list1(a)
print(b) ## [5, 7, 0, 3, 1, 8, 4, 2, 6, 9]
# 方案2
def random_list2(a):
a_copy = a.copy() # 先复制一份
result = []
count = len(a) #得到a的长度
for i in range(0,count):
index = random.randint(0, len(a_copy) - 1)
result.append(a_copy[index]) #随机得到a中一个元素存到结果中
del a_copy[index] # 删除这个随机的幸运儿元素 直到全部删除完,结束循环
return result
a = [1,2,3,4,5,6,7, 8, 9,0 ]
b = random_list2(a)
print(b) ## [5, 2, 6, 7, 0, 1, 9, 8, 3, 4]
4个区别
# 1:语法差异
a = (1,2,3,4) # 元组
b = [1,2,3,4] # 列表
# 2:元组是只读的,列表是可读写的
b[1] = 3
# 3.
copy_a = tuple(a) # 元祖拷贝结果是元祖自身
print(a is copy_a) # True
copy_b = list(b) # 列表拷贝会生成一个新的列表
print(b is copy_b) # False
# 4:大小不同,元组占用的空间更小(大的内存块)
print(a.__sizeof__()) #56
print(b.__sizeof__()) #72
a = [1,2,3,4,5,6,7, 8, 9,0 ]
random.shuffle(a) ##调用python模块中现成方法
print(a) ## [3, 0, 8, 1, 5, 7, 4, 6, 9, 2]
编写一个函数(不使用Python模块中的函数),打乱列表元祖的顺序 #30
*和**的作用
# 单星(*)
# 以元组形式导入
# 可变参数
# 如果可变参数不是最后一个参数,那么为可变参数后面的形参指定参数值,必须用命名参数
def fun1(param1, *param2,x): ##带*为可变参数
print('param1:',param1)
print('param2:',param2,type(param2)) ## type 获取数据类型
print('x:',x)
fun1(1,2,3,4,5,x = 6)
## param1: 1
## param2: (2, 3, 4, 5) <class 'tuple'>
## x: 6
# 双星号(**)
# 以字典形式导入 key 和 value
def fun2(param1, **param2):
print('param1:',param1)
print('param2:',param2,type(param2))
fun2(1,a = 2,b = 3,c = 4,d = 5)
## param1: 1
## param2: {'a': 2, 'b': 3, 'c': 4, 'd': 5} <class 'dict'>
import sys
sys.path.append('/MyPythonDemo/modules')
import working
print(working.greet('Bill'))
让转义符失效(3种方法: r、repr和\)
print(r'Let \'s go!') ## Let \'s go!
print(repr('hello\nworld')) ## 'hello\nworld'
print('hello\\nworld') ## hello\nworld
print(format(x2,'*>15.4f')) # 右对齐,********30.1000
print(format(x2, '*<15.4f')) # 左对齐,30.1000********
print(format(x2, '*^15.4f')) # 中心对齐,****30.1000****
print(format(123456789,',')) # 用千位号分隔,123,456,789
print(format(1234567.865565656,',.2f')) # 1,234,567.87
print(format(x1,'E')) # 1.234568E+03
print(format(x1,'0.2E')) # 1.23E+03
n = 1234
print(format(n, '10d')) ## 1234 前面补空格
print(format(n, '0>10d')) ## 0000001234
print(format(n, '0<10d')) ## 1234000000
## 以下列表和字典不能作为字典键值
#d[[1,2,3]] = 3 ## TypeError: unhashable type: 'list'
#d[{'a:',3}] = 4 ## TypeError: unhashable type: 'set'
因为key是不能变的。但列表和字典的值是可以变化的,一旦变化,就再也找不到对应的value了
由于列表和字典的元素是可变的,所以不能作为字典的键值
s1 = '12345'
print('12345是数字:',s1.isdigit()) ##12345是数字: True
print(int(s1)) ##12345
s2 = '12345a'
print('12345a是数字:',s2.isdigit()) ##12345a是数字: False
print('12345a是字母数字混合形式:',s2.isalnum()) ##12345a是字母数字混合形式: True
s3 = '12_345a'
print('12_345a是字母数字混合形式:',s3.isalnum()) ##12_345a是字母数字混合形式: False
print(" ".isspace()) ## True
print("12.45".isdecimal()) # 检测字符串中是否为整数 ## False
print("abc3d".isalpha()) # 检测字符串中是否为纯字母 ## False
集合之间的运算
x1 = {1,2,3}
x2 = {3,4,5}
print('x1和x2合并:',x1 | x2) # 集合之间的合并 ## x1和x2合并: {1, 2, 3, 4, 5}
print('x1和x2合并:',x1.union(x2)) ## x1和x2合并: {1, 2, 3, 4, 5}
print('x1和x2相交:', x1 & x2) # 集合之间的相交 ## x1和x2相交: {3}
print('x1和x2相交:', x1.intersection(x2)) ## x1和x2相交: {3}
print(x1.difference(x2)) # 将x1中有的,在x2中也有的删除,返回值是x1的子集合
## {1, 2}
print(x1 ^ x2) # 刨除x1和x2共用的元素,返回值是集合并的子集 ## {1, 2, 4, 5}
a = [i for i in range(10)]
print(a) ## [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(type(a)) ## <class 'list'>
b = (i for i in range(10))
print(b) ## <generator object <genexpr> at 0x000002DA29D851B0>
print(type(b)) ## <class 'generator'>
for i in a:
print(i)
for i in b:
print(i * i)
x = (1,2,3,4)
print(type(x)) ## <class 'tuple'>
如果列表是通过for循环产生的,只需要将方括号变成圆括号,就会将列表变成一个产生器。
a = [4,3,6,5]
print(a) #[4, 3, 6, 5]
del(a[2])
print(a) # [4, 3, 5]
print(a.pop(1)) # 3 删除角标为1的元素
print(a) # [4, 5]
print(a.pop()) # 5 不传参数,默认删除最后一个元素
print(a) # [4]
# del 根据索引删除列表元素,但没有返回值
# pop 根据索引弹出列表元素,并返回该元素,同时从列表中删除该元素
del是一个关键字,可以根据索引删除列表中的元素,没有返回值
pop是列表的一个方法,可以根据索引弹出并返回列表中的元素,同时删除
这个元素
添加和删除集合中的元素
x = {3,2,1}
x.add(123) ## 添加元素
print(x) ## {123, 1, 2, 3}
x.add(1) ## 集合中添加重复元素,结果不会重复元素
print(x) ## {123, 1, 2, 3}
x.add('abc') ## 集合中可包含不同数据类型的元素
print(x) ## {1, 2, 3, 'abc', 123} 不是按顺序存储
x.remove(123) ## 删除元素
if x.__contains__(444): ## 删除元素前应先判断是否存在,删除不存在的元素会抛出异常
x.remove(444)
else:
print('444在集合中不存在')
print("aa","bb",sep=",") ## aa,bb
print("aa","bb",sep="*") ## aa*bb
from itertools import islice
gen = iter(range(10))
print(type(gen)) ## <class 'range_iterator'>
for i in islice(gen,2,6):
print(i)
# 2
# 3
# 4
# 5
itertools模块中的islice函数可以使用分片获取产生器类型对象中的部分元素
islice函数的第一个参数是产生器,第2个参数是开始索引,第3个参数是结束索引的下一个元素的索引
如何将两个列表或元祖和并成一个字典,形式如下:
a = ['a','b'] #列表1
b = [1,2] #列表2
# 合并后:{'a':1,'b':2}
a = ['a','b']
b = [1,2]
print(dict(zip(a,b)))
{'a': 1, 'b': 2}
扩展:
fields = ('id','name','age') # 相当于数据库表头
records = [['01','Bill','20'],['02','Mike','30']] # 相当于数据库行数据
result = []
for record in records:
result.append(dict(zip(fields,record)))
print(result)
[
{'id':'01','name':'Bill','age':'20'},
{'id':'02','name':'Mike','age':'30'},
]
s = 'road'
x = len(s)
print('The length of %s is %d' % (s,x)) ## The length of road is 4
from io import StringIO
import sys
old_stdout = sys.stdout
result = StringIO()
sys.stdout = result
print('The length of %s is %d' % (s,x))
sys.stdout = old_stdout
result_str = result.getvalue()
print('result_str',result_str,sep=':') ## result_str:The length of road is 4
x1 = 1234.56789
x2 = 30.1
print(format(x1, '0.2f')) # 保留小数点后两位 ## 1234.57
print(format(x2,'0.2f')) ## 30.10
进制之间的转换
# 十进制转换为二进制
print(bin(120))
# 将二进制转为十进制
print(int('0B10110',2))
print(int('10110',2))
# 十六进制转十进制
print(int('0XF35AE',16))
print(int('F35AE',16))
# 十进制转为十六进制
print(hex(54321))
# 十六进制转换为二进制
print(bin(0xF012A))
# 将二进制转换为十六进制
print(hex(0b1101110101))
# 十进制转为八进制
print(oct(1234))
# 将八进制转为十进制
print(int('3213',8))
# 输出仍然是十进制
print(0b11010101 * 0XF12 * 0o432 * 123)
print('hello',end=' aa')
print('world')
hello aaworld
第1种:+(加号)
s1 = 'hello'
s2 = 'world'
s = s1 + s2
print(s)
helloworld
2: 直接连接
s = "hello""world"
print(s)
helloworld
3:用逗号(,)连接,标准输出的重定向
from io import StringIO
import sys
old_stdout = sys.stdout
result = StringIO()
sys.stdout = result
print('hello','world')
sys.stdout =old_stdout # 恢复标准输出
result_str = result.getvalue()
print("用逗号连接:",result_str)
用逗号连接: hello world
4:格式化
s = '<%s> <%s>' % (s1,s2)
print('格式化:',s)
格式化: < hello > < world >
5: join
s = " ".join([s1,s2])
print("join连接:",s)
join连接: hello world
如何合并列表和字典
# 列表
a = [1,2,3]
b = [4,5,6]
# 1
c = a + b
print(c) # [1, 2, 3, 4, 5, 6]
# 2
a.extend(b)
print(a) # [1, 2, 3, 4, 5, 6]
a = [1,2,3]
b = [4,5,6]
# 3
x = [a,b]
print(x) # [[1, 2, 3], [4, 5, 6]]
x = [*a, *b]
print(x) #[1,2,3,4,5,6]
# 字典
a = {'A':1,'B':2}
b = {'B':2,'C':3,'D':4}
# c = {'A':1,'B':2,'C':3,'D':4}
c = {**a,**b}
print(c) # {'A': 1, 'B': 2, 'C': 3, 'D': 4} #重复的会覆盖
导入Python模块的方式
import math #导入math包
print(math.sin(1.23))
from math import cos,tan #仅导入math包中的cos和tan
#直接使用cos函数,不用再加`math.`了,
#如果还加`math.`就会抛出异常 `NameError: name 'math' is not defined`
print(cos(2.34))
print(tan(1.23))
from math import * #导入math包中全部函数
#直接使用cos函数,不用再加`math.`了
#如果还加`math.`就会抛出异常 `NameError: name 'math' is not defined`
print(cos(2.34))
print(tanh(1.23))
# 列表和字典类型不能作为字典的键值
d = {}
d['name'] = 'Bill'
d[10] = 20
d[True] = False
d[12.3] = 20.1
d[(1,2,3)] = [4,5,6]
class Person:
pass
p1 = Person()
p2 = Person()
d[p1] = "p1"
d[p2] = 'p2'
print(d)
print(d[12.3])
## 以下列表和字典不能作为字典键值
#d[[1,2,3]] = 3 ## TypeError: unhashable type: 'list'
#d[{'a:',3}] = 4 ## TypeError: unhashable type: 'set'
因为key是不能变的。但列表和字典的值是可以变化的,一旦变化,就再也找不到对应的value了
由于列表和字典的元素是可变的,所以不能作为字典的键值
1:加号
n = 20
s = s1 + str(n)
print(s)
v = 12.44
b = True
print(s1 + str(n) + str(v) + str(b))
hello20
hello2012.44True
2: 格式化
s = '<%s> <%d> <%.2f>' %(s1,n,v)
print('格式化:',s)
格式化:
<hello> <20> <12.44>
3:重定向
from io import StringIO
import sys
old_stdout = sys.stdout
result = StringIO()
sys.stdout = result
print(s1, True, n,v,sep='*') #设置分隔符为 *
sys.stdout =old_stdout # 恢复标准输出
result_str = result.getvalue()
print("用逗号连接:",result_str)
用逗号连接:
hello*True*20*12.44
# 十进制
n1 = 1234
# 二进制
n2 = 0B11101
print(n2) # 29
# 八进制
n3 = 0O127
print(n3) # 87
# 十六进制
n4 = 0XF15
print(n4) # 3861
其中
b
、o
、x
不区分大小写
a = [1,2,2,3,4,3]
a_result = list(set(a)) # 先转换成集合,集合中不包含重复元素,再转回 list列表
print(a_result) ## [1, 2, 3, 4]
print(type(a_result)) ## <class 'list'>
print(tuple(set(a))) ## (1, 2, 3, 4)
使用三对"
或'
让字符串原样输出:
print("""
hello
world
I love you.
""")
hello
world
I love you.
如何快速调换字典中的key和value
d = {'a':1,'b':2}
print({v:k for k,v in d.items()}) # {1: 'a', 2: 'b'}
s1 = 'hello'
class MyClass:
def __str__(self):
return 'This is a MyClass Instance.'
my = MyClass()
s = s1 + str(my)
print(s)
helloThis is a MyClass Instance.
s3 = 'hello world'
print(s3.capitalize()) ## Hello world
arr = s3.split(' ')
new_str = f'{arr[0].capitalize()} {arr[1].capitalize()}'
print(new_str) ## Hello World
给模块指定别名 as
import math as m
print(m.sin(20))
#print(math.sin(20)) # NameError: name 'math' is not defined
from math import cos as c
print(c(3)) #这里的`c`指代的就是`math.cos`
print(cos(12)) #虽然指定了别名,但原名依然可用
降序排列
a = [5,4,2,7,3,8,3]
b = [6,4,3,3,76,2,234]
a.sort(reverse=True) # reverse=True 指定降序排列,默认false升序
print(a) # [8, 7, 5, 4, 3, 3, 2]
print(sorted(b,reverse=True)) # reverse=True 指定降序排列,默认false升序
# [234, 76, 6, 4, 3, 3, 2]
s1 = 'hello'
print(s1) ## hello
print(s1.capitalize()) ## Hello
# s1[0] = 'H' 只读的,会抛出异常
s1 = s1[0:1] + s1[1].upper() + s1[2:]
print(s1) ## hEllo
s2 = 'Hello'
s = s2[0].lower() + s2[1:]
print(s) ## hello
sort和sorted的区别
你可以把面试中或工作中遇到的问题提报在此,让我们共同探讨,共同进步!
tks!
同时输出单引号和双引号
print('hello "world"') ## hello "world"
print("hello 'world'") ## hello 'world'
print('"hello" \'world\'') ## "hello" 'world'
class MyClass:
def __init__(self):
self.value = 0
def __gt__(self, other):
return self.value > other.value
'''
def __lt__(self, other):
return self.value > other.value
'''
my1 = MyClass()
my1.value = 20
my2 = MyClass()
my2.value = 10
my3 = MyClass()
my3.value = 30
a = [my1,my2,my3]
print(a)
# [<__main__.MyClass object at 0x0000026B3FD5DA90>, <__main__.MyClass object at 0x0000026B3FD5DB00>, <__main__.MyClass object at 0x0000026B3FD5DB70>]
import operator
#a.sort() #
a.sort(key = operator.attrgetter('value')) # 根据对象的 value 排序
b = sorted(a,key = operator.attrgetter('value'))
降序排序
#a.sort(key = operator.attrgetter('value'),reverse=True) # 根据对象的 value 排序 reverse=True 降序
a.sort()
print(a[0].value)
print(a[1].value)
print(a[2].value)
为类添加__gt__和__lt__方法,可以让该类的实例支持sort方法和sorted函数
通过改变__gt__和__lt__方法的返回值,或者设置sort方法和sorted函数的reverse参数,可以让列表倒序排列。
s1 = "1234"
print(int(s1)) ## 1234
s2 = '1234a'
#print(int(s2)) ## ValueError: invalid literal for int() with base 10: '1234a'
# 先判断数据类型
if s2.isdigit():
print(int(s2))
else:
print('s2不是数字,无法转换')
# 捕捉异常
try:
print(int('223aaa'))
except Exception as e:
print('223aaa不是数字,无法转换')
print(e)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.