30道python真实面试题(搜集到的,看看其实都是基础)

1、一行代码实现1-100之间和

In [1]: sum(range(0,101))
Out[1]: 5050

2、如何在一个函数内部修改全局变量

利用global修改全局变量

In [2]: a = 10
In [3]: def fn():
   ...:     global a
   ...:     a=4
   ...:
In [4]: fn()
In [5]: print(a)
4
3、列出5给python标准库

os:提供了不少与操作系统相关联的函数
sys:通常用于命令行参数
re:正则表达式
math:数学运算
datetime:处理日期时间

4、字典如何删除和合并字典

使用字典的方法del和update

In [6]: dict1 = {1:'one',2:'two',3:'three'}
In [7]: del dict1[1] #删除字典的键值
In [8]: dict1
Out[8]: {2: 'two', 3: 'three'}
In [9]: dict2 = {4:'four',5:'five'}
In [10]: dict1.update(dict2)  #update合并字典
In [11]: dict1
Out[11]: {2: 'two', 3: 'three', 4: 'four', 5: 'five'}

5、谈下python的GIL

GIL是python的全局解释器锁,同一进程中假如有多个线程运行,一个线程在运行python程序的时候会霸占python解释器(加一把锁即GIL),使该进程内的其他线程无法运行,等该线程运行完后其他线程才能运行。如果线程运行过程中遇到耗时操作,则解释器锁解开,使其他线程进行。所以在多线程中,线程的运行仍是有先后顺序的,并不是同时进行。

多进程中因为每个进程都能被系统分配资源,相当于每个有一个python解释器,所以多进程可以实现多个进程的同时运行,缺点是进程系统资源开销大。

6、python实现列表去重的方法

先通过集合去重,后再转换为列表

In [20]: list1 = [4,6,3,4,12,7,5,8]
In [21]: a = set(list1)   #转换为集合
In [22]: a
Out[22]: {3, 4, 5, 6, 7, 8, 12}
In [23]: [x for x in a]
Out[23]: [3, 4, 5, 6, 7, 8, 12]

7、fun(*args,**kwargs)中的*args,**kwarg什么意思?

*args,**kwargs主要用于函数定义,可以将不定数量的参数传递给一个函数,这里的不定意思是:预先并不知道函数使用者会传递多少个参数,所以在这个场景下使用这两个关键字。*args是用来发送一个非键值对的可变数量的参数列表给函数,来看个例子

In [24]: def dome(arg,*args):
    ...:     print(arg)
    ...:     for i in args:
    ...:         print(i)
    ...:

In [25]: dome(1,5,7,3,8)
1
5
7
3
8

**kwargs允许将不定长度的键值对作为参数传递给一个函数,如想要在一个函数里处理带名字的参数,这时就要使用**kwargs,上个例子

In [28]: def demo(**kwargs):
    ...:     for k,v in kwargs.items():
    ...:         print(k,v)
    ...:

In [29]: demo(name='marry',age='女')
name marry
age 女

8、python2和python3的range(100)区别

python2返回列表

python3返回迭代器,节约内存

9、一句话解释什么样的语言能够使用装饰器?

函数可以作为参数传递语言,可以使用装饰器

10、python内建数据类型那些

整型--int
布尔型--bool
字符串--str
列表--list
元组--tuple
字典--dict

11、简述面向对象中__new__和__init__区别

__init__是初始化方法,创建对象后,就立刻被默认调用了,可以接收参数,如所示

In [41]: class demo_new:
    ...:     def __init__(self,newnum,newcolor):  #__init__方法自动被调用,可以接收参数
    ...:         self.newnum = newnum
    ...:         self.newcolor = newcolor
    ...:     def move(self):
    ...:         print('飞起来')
    ...:

In [42]: demo1 = demo_new(2,'green')  #创建对象
In [43]: print(demo1.newcolor)
green
In [44]: print(demo1.newnum)
2

(1)__new__至少要有一个参数cls,当前类,此参数在实例化时由python解释器自动识别

(2)__new__必须要有返回值,返回实例化出来的实例,这点在自己实现__new__时要特别注意,可以return父类(通过super(当前类名,cls))__new__出来的实例,或者直接是object的__new__出来的实例

(3)__init__有一个参数self,就是__new__返回的实例,__init__在__new__的基础上可以完成一些其他初始化动作,__init__不需要返回值

(4)如果__new__创建的是当前类的实例,会自动调用__init__函数,通过return语句里面调用__new__函数的第一个参数是cls来保证是当前类实例,如果是其他类的类名,那么实际创建返沪的就是其他类的实例,其实就不会调用其他类__init__函数

In [46]: class A(object):
    ...:     def __init__(self):
    ...:         print('__init__方法',self)
    ...:     def __new__(cls):
    ...:         print('这是cls的ID',id(cls))
    ...:         print('这是__new__方法',object.__new__(cls))
    ...:         return object.__new__(cls)
    ...:

In [47]: A()
这是cls的ID 2069068533960
这是__new__方法 <__main__.A object at 0x000001E1BEE0BE48>
__init__方法 <__main__.A object at 0x000001E1BEE0BE48>
Out[47]: <__main__.A at 0x1e1bee0be48>
In [48]: print('这是类A的ID',id(A))
这是类A的ID 2069068533960

12、简述with方法打开处理文件帮我们做了什么

In [50]: f = open('./1.txt','wb')
In [51]: try:
    ...:     f.write('hello world')
    ...: except:
    ...:     pass
    ...: finally:
    ...:     f.close()

打开文件在进行读写的时候可能会出现一些异常状况,如果汉族常规的f.open写,我们需要try,excpet,finally做异常判断,并且文件最终不管遇到什么情况,都要执行finally f.close()关闭文件,with方法帮我们实现了finally中的f.close()

13、列表[1,2,3,4,5],请使用map()函数输出[1,4,9,16,25],并使用列表推导式提取出大于10的数,最终输出[16,25]

map()函数第一个参数是fun,第二个参数一般是list,第三个参数可以写list,也可不写

In [52]: list1 = [1,2,3,4,5]
In [53]: def fn(x):
    ...:     return x**2
    ...:
In [54]: res = map(fn,list1)
In [55]: res = [i for i in res if i >10]
In [56]: print(res)
[16, 25]

14、python中生成随机整数、随机销售,0-1之间的小数方法

随机整数:random.randint(a,b)  区间整数
随机小数:用numpy库,利用np.random.randn(5)  生成5个随机小数
0-1随机小数:random.random(),注:括号内不传参

15、避免转义给字符串加那个字母表示原始字符串:

r,表示需要原始字符串,不转义特殊字符

16、<div class=’nam’>中国</div>,用正则匹配出标签里面的内容(‘中国’),其中class的类名不确定

In [67]: import re
In [68]: str1 = '<div class="nam">中国</div>'
In [69]: res = re.findall(r'<div class=".*">(.*?)</div>',str1)
In [70]: print(res)
['中国']

17、python中断言方法举例

assert()方法,断言成功,则程序继续执行,断言失败,则程序报错

In [71]: a = 3
In [72]: assert(a>1)
In [73]: print("断言成功,程序继续向下执行")
断言成功,程序继续向下执行
In [74]: b = 5
In [75]: assert(b>9)
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-75-e543486a620d> in <module>
----> 1 assert(b>9)
AssertionError:

18、数据表student有id,name,score,city字段,其中name中有名字可能重复,需要消除重复行,请写sql语句

select distinct name from student

19、10个Linux常用命令

ls pwd cd touch rm mkdir tree cp mv cat more grep echo

20、python2和python3区别?

(1)python3使用print必须用小括号包裹打印内容

(2)python2 range(10)返回列表,python3返回迭代器,节约内存

(3)python2使用ascii编码,python3使用uft-8编码

(4)python2中unicode表示字符串序列,str表示字节序列;python3中str表示字符串学历,byte表示字节序列

(5)python2中正常显示中文,引入coding声明,python3不需要

(6)python2中raw_input()函数,python3中是input()函数

21、列出python中可变数据类型和不可变数据类型,简述原理

不可变数据类型:数值型、字符串型string和远祖tuple

不可变数据类型:不允许变量的值发生变化,如果改变了变量的值,相当于新建了一个对象,而对于相同的值的对象,内存中则只有一个对象地址,可用id()方法查看

可变数据类型:列表list和字典dict

允许变量的值发生变化,即如果对变量进行了append、+=等操作后,只是改变了变量的值,而新建对象,变量引用的地址也不会变化,不过对于相同的值的不同对象,在内存中则会存在不同的对象,即,每个对象都有自己的地址,相当于内存中对于同值的对象保存了多份,这里不存在引用计数,是实实在在的对象。

In [76]: a = 3
In [77]: b = 3
In [78]: id(a)
Out[78]: 1608819872
In [79]: id(b)
Out[79]: 1608819872
In [80]: a = [1,2]
In [81]: b = [1,2]
In [82]: id(a)
Out[82]: 2069075295752
In [83]: id(b)
Out[83]: 2069084580424

22、s=’abcadbdx’,去重并从小到大排序‘abcdx’

In [85]: s = 'abcadbdx'
In [86]: s = set(s)
In [87]: s = list(s)
In [88]: s.sort(reverse=False)
In [89]: res = ''.join(s)
In [90]: print(res)
abcdx

23、用lambda函数实现两个数相乘

In [91]: sum1 = lambda a,b:a*b
In [92]: print(sum1(4,5))
20

24、字典根据键从小到大排序dict1=

{'name':'sx','age':5000,'city':'西安','tel':'132xxxxxxxxx'}

In [93]: dict1 = {'name':'sx','age':5000,'city':'西安','tel':'132xxxxxxxxx'}
In [94]: list1 = sorted(dict1.items(),key=lambda i :i[0],reverse=False)
In [95]: print('sorted根据字典键排序',list1)
sorted根据字典键排序 [('age', 5000), ('city', '西安'), ('name', 'sx'), ('tel', '132xxxxxxxxx')]
In [96]: new_dict = {}
In [97]: for i in list1:
    ...:     new_dict[i[0]]=i[1]
    ...:
In [98]: print('新字典',new_dict)
新字典 {'age': 5000, 'city': '西安', 'name': 'sx', 'tel': '132xxxxxxxxx'}

25、字符串a =’not 404 found 张三 99 西安’,每个词中间都有空格,用正则过滤掉英文和数字,最终输出;张三 深圳

In [106]: import re
In [107]: a = 'not 404 found 张三 99 西安'
In [108]: list1 = a.split(" ")
In [109]: print(list1)
['not', '404', 'found', '张三', '99', '西安']
In [110]: res = re.findall('\d+|[a-zA-Z]+',a)
In [111]: for i in res:
     ...:     if i in list1:
     ...:         list1.remove(i)
     ...:
In [112]: new_str = " ".join(list1)
In [113]: print(res)
['not', '404', 'found', '99']
In [114]: print(new_str)
张三 西安

26、用filter方法求出列表所有奇数,并构造新列表,a = [1,2,3,4,5,6,7,8,9,10]

filter()函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素构成的新列表。该接收两个参数,第一个为函数,第二个位序列,序列的每个元素作为参数传递给函数进行判断,返回True或False,最后将返回为True的放到中

In [115]: a = [1,2,3,4,5,6,7,8,9,10]
In [116]: def fn(a):
     ...:     return a%2==1
     ...:
In [117]: newlist = filter(fn,a)
In [118]: newlist = [i for i in newlist]
In [119]: print(newlist)
[1, 3, 5, 7, 9]

27、列表推导式求列表所有奇数,并构造新列表,a=[1,2,3,4,5,6,7,8,9,10]

In [120]: a = [1,2,3,4,5,6,7,8,9,10]
In [121]: res = [i for i in a if i%2==1]
In [122]: print(res)
[1, 3, 5, 7, 9]

28、正则re.complie作用

re.complie是将正则表达式编译成一个对象,加快速度,并重复使用

29、a=(1,),b=(1),c=(‘1’)分别表示什么类型数据

In [123]: type((1,))
Out[123]: tuple

In [124]: type((1))
Out[124]: int

In [125]: type(('1'))
Out[125]: str

30、利用collections库的Counter方法统计字符串每个单词出现的次数

In [130]: from collections import Counter
In [131]: a = 'aksfnwoefjaonfakfasojf;sfhwnafsn;sfhowsjfaoemsm,'
In [132]: res = Counter(a)
In [133]: print(res)
Counter({'f': 9, 's': 7, 'a': 6, 'o': 5, 'n': 4, 'w': 3, 'j': 3, 'k': 2, 'e': 2, ';': 2, 'h': 2, 'm': 2, ',': 1})

猜你喜欢

转载自www.cnblogs.com/pinpin/p/10080039.html