程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Summary of Python interview questions (I)

編輯:Python

1、 One line of code 1-100 And

print(sum(range(1,101)))
5050

2、 How to modify global variables inside a function

a=10
def func():
a=20
print(a)
func()
print(a)

Execution results :20,10

a=10
def func():
global a
a=20
print(a)
func()
print(a)

Execution results :20,20

3、 List 5 individual python Standard library

import os
import sys
import time
import datetime
import random
import re

4、 How dictionaries delete keys and merge 2 A dictionary

Delete key

Method 1 : Use pop()
Method 2 : Use del

dic = {
'a': 1, 'b': 2}
dic1 = {
'c': 3, 'd': 4}
dic.pop('b')
print(dic)
del dic1['c']
print(dic1)

Merge dictionaries

update: You can merge dictionaries

dic = {
'a': 1, 'b': 2}
dic1 = {
'c': 3, 'd': 4}
dic.update(dic1)
print(dic)

Execution results :{‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}

5、 go on talking python Of GIL

Multithreads in a process share data in the process , In a single cpu Within the time frame , If a thread has not finished executing , And there is no continuity cpu Time slice , At this point, the subsequent thread also starts to execute the task , There will be data confusion , That is, the thread is not safe . resolvent : Lock , Ensure that only one thread is executing a task at a certain time .

6、2 A list to achieve list de duplication

li=[2,3,4,5,6]
li1=[4,5,6,7,8]
li.extend(li1)
ll=list(set(li))
print(ll)

7、fun(*args,**kwargs) Medium *args,**kwargs What does that mean?

*args: Receive all unmatched position parameters in the actual parameters
**kwargs: Receive all unmatched keyword parameters in the actual parameters

8、 Explain in one sentence what language can use decorators

Functions can be passed as parameters

9、python What are the built-in data types ?

str
int
float
bool
list
tuple
dict
set

10、 In this paper, a brief introduction of object-oriented is given __new__ and __init__ difference

__new__:

a、 For creating objects , Give the created object to __init__ Method
b、 Pass at least one parameter cls, Represents the current class
c、 There must be a return value , Return the instantiated instance

__init__:

a、 Used to initialize objects , The prerequisite is that the object must be created , Once the object is created, it is called by default , Can receive parameters .
b、 The first parameter bit self, This is this. __new__ The returned instance ;__init__ stay __new__ Can complete some other initialization actions on the basis of
c、__init__ You don't need to return a value
d、 If __new__ Create an instance of the current class , Automatically called __init__ function , adopt return Statement __new__ First argument to function cls To ensure that it is the current class instance ; If it's the class name of another class , Then the actual creation returns instances of other classes , In fact, the current class will not be called __init__ function , No other classes will be called __init__ function .

11、 sketch with Method to open the processing file to help us do ?

If you use conventional f.open() How to write it , We need to try、except、finally, Make abnormal judgment , And in the end, whatever happens to the file , To perform all finally f.close() Close file .

f=open('./1.txt','w')
try:
f.write("hello")
except:
pass
finally:
f.close()

Use with Method

with open('a.txt') as f:
print(f.read())

perform with After this structure .f It will automatically turn off . It's equivalent to bringing a finally.
however with There is no exception capture function in itself , But if a runtime exception occurs , It can still close files and free resources .

12、 list [1,2,3,4,5], Please use map() Output function [1,4,9,16,25], And use list derivation to extract more than 10 Number of numbers , Final output [16,25]

Method 1 :

a=[1,2,3,4,5]
def func1(x):
return x**2
aa=map(func1,a)
new_aa=[i for i in aa if i>10]
print(new_aa)

Method 2 :

l=[1,2,3,4,5]
ll=list(map(lambda x:x*x,l))
lll=[i for i in ll if i>10]
print(lll)

13、python To generate random integers 、 Random decimal 、0-1 Decimal between

random.random(): Random generation 0 To 1 Decimal between
:.3f: Retain 3 Significant digits

import random
num=random.randint(1,6)
num1=random.random()
print(num)
print(num1)
print('{:.3f}'.format(num1))

14、python Examples of interruptions

a=3
assert(a>1)
print(a) #3
a=3
assert(a>6)
print(a)

Assertion failed

Traceback (most recent call last):
File "D:\log\ceshi_log\face_1.py", line 64, in <module>
assert(a>6)
AssertionError

15、 List python Variable data type and immutable data type in , And briefly describe the principle

The history blog has detailed answers , Assignment by value and assignment by reference

16、 De duplication and sort output from small to large “adfjl”

Collection can de duplicate strings

s = 'ajldjlajfdljfddd'
s1=list(set(s))
s1.sort()
s2=''.join(s1)
print(s2)

Particular attention : Out of commission split() Method

s1=s.split()
print(s1)
['ajldjlajfdljfddd']

17、 use lambda Function to multiply two numbers

sum=lambda a,b:a*b
print(sum(3,4))
12

18、 Dictionaries are sorted by key from small to large

dict1.items(): Get the key value in the dictionary , And keys and values are combined into a tuple

dict1={
"name":"zs","city":"beijing","tel":1243124}
print(dict1.items())
dd=sorted(dict1.items(),key=lambda x:x[0])
print(dd)
new_dict={
}
for item in dd:
new_dict[item[0]]=item[1]
print(new_dict)

19、 utilize collections Library Counter Method to count the number of occurrences of each word in the string

Count the number of occurrences of each word in the string :
from collections import Counter
res=Counter(a)

from collections import Counter
a="werwerwegdfgerwewed;wer;wer;6"
from collections import Counter
res=Counter(a)
print(res)

Execution results :
Counter({‘e’: 8, ‘w’: 7, ‘r’: 5, ‘;’: 3, ‘g’: 2, ‘d’: 2, ‘f’: 1, ‘6’: 1})

20、filter Method to find all the odd numbers in the list and construct a new list

a=[1,2,3,4,5,6,7,8,9,10]
def func(x):
return x%2==1
newlist=filter(func,a)
newlist=[i for i in newlist]
print(newlist)

Execution results :
[1, 3, 5, 7, 9]

21、 List derivation finds all odd numbers in the list and constructs a new list

a=[1,2,3,4,5,6,7,8,9,10]
aa=[i for i in a if i%2==1]
print(aa)

Execution results :
[1, 3, 5, 7, 9]

22、a=(1,) b=(1) c=(‘1’) What types are they

a=(1,)
b=(1)
c=('1')
print(type(a))
print(type(b))
print(type(c))

Execution results :
<class ‘tuple’>
<class ‘int’>
<class ‘str’>

23、 The two lists are merged into one list

List together : Merge list
extend

a=[1,3,4,5,6]
b=[1,3,56,7,7,5]
c=a+b
a.extend(b)
a.sort()
print(c)
print(a)

24、[[1,2],[3,4],[5,6]] Expand to get [1,2,3,4,5,6]

l=[[1,2],[3,4],[5,6]]
new_list=[]
for item in l:
for i in item:
new_list.append(i)
print(newlist)

Execution results :
[1, 3, 5, 7, 9]

25、x=“abc”,y=“def” z=[“d”,“e”,“f”], seek x.join(y),x.join(z) The result returned

join(): In parentheses are iteratable objects ,x Insert in the middle of an iteratable object , Form a string , Consistent result

x = "abc"
y = "def"
z = ["d", "e", "f"]
x_1=x.join(y)
print(x_1)
x_2=x.join(z)
print(x_2)

26、 For example, in the exception module try except else finally The relevance of

try except else No exception was caught , perform else sentence
try except finally Whether or not an exception is caught , All implemented finally sentence

27、python China exchange 2 A numerical

a=12
b=23
a,b=b,a
print(a)
print(b)

28、 Illustrate with examples zip Function usage

a、zip() Function in operation , In one or more sequences ( Iteratable object ) As a parameter , Returns a list of tuples , At the same time, pair the elements side by side in these sequences .
b、zip() Function can receive any type of sequence , There can also be 2 More than parameters ; When the parameters passed in are different ,zip It can automatically intercept the shortest sequence , Get tuple .

a=[1,2,3]
b=[5,6,7]
res=list(zip(a,b))
print(res)
a=(1,2,3)
b=(5,6,7)
res1=list(zip(a,b))
print(res1)
a=(1,2)
b=(5,6,7)
res2=list(zip(a,b))
print(res2)

Execution results :
[(1, 5), (2, 6), (3, 7)]
[(1, 5), (2, 6), (3, 7)]
[(1, 5), (2, 6)]

29、 List together

print([1,2,3]+[4,5,6])
print([1,2,3]+[3,4,5,6])

[1, 2, 3, 4, 5, 6]
[1, 2, 3, 3, 4, 5, 6]

30、 promote python The way to run efficiency

1、 Adopt generator , Do not use lists and list derivations , Save a lot of memory
2、 Multiple if elif else Conditional statements , Write the most likely conditions first , This can reduce the number of program judgments , Increase of efficiency .
3、 Loop code optimization , Avoid too much repetitive code execution
4、 Multi process 、 Multithreading 、 coroutines

31、 sketch mysql and redis difference

redis: Memory non relational database , Data is stored in memory , Fast
mysql: Relational database , The data is stored on disk , Search words , There will be a certain amount of IO operation , The access speed is relatively slow

32、list=[2,3,5,4,9,6], Sort from small to large , Don't use sort, Output [2,3,4,5,6,9]

list1=[2,3,5,4,9,6]
def list_str(list):
num=len(list)
for i in range(num-1):
for j in range(num-1-i):
if list[j]>list[j+1]:
list[j],list[j+1]=list[j+1],list[j]
print(list)
list_str(list1)

[2, 3, 4, 5, 6, 9]

33、 Write a singleton pattern

class Create_Object:
obj=None
def __new__(cls, *args, **kwargs):
if obj is None:
cls.obj=super().__new__(cls)
return cls.obj
object=Create_Object
object1=Create_Object
print(id(object))
print(id(object1))

2944204723184
2944204723184

34、 Achieve retention 2 Decimal place

round(3.1415926,2):2 Means to keep the decimal point 2 position

num='{:.2f}'.format(3.4564564)
print(num)
num1=round(3.4564564,3)
print(num1)

3.46
3.456

35、 seek 3 Print results of methods

fn(“one”,1): Pass the key value directly to the dictionary
fn(“two”,2): Because dictionaries are variable data types , So it points to the same memory address , After passing in the new parameter , It is equivalent to adding value to the dictionary
fn(“three”,3,{}): A new dictionary has been passed in , So it is no longer the default dictionary

def fn(k,v,div={
}):
div[k]=v
print(div)
fn("one",1)
fn("two",2)
fn("three",3,{
})

{‘one’: 1}
{‘one’: 1, ‘two’: 2}
{‘three’: 3}

36、 How to create a dictionary

a=[("a",1),("b",2),("c",3),("d",4),("e",5)]
A=zip(("a","b","c","d","e"),(1,2,3,4,5))
print(dict(A))
B=dict([["name","zs"],["age",18]])
C=dict([("name","ls"),("age",20)])
print(B)
print(C)

37、 Deep copy and light copy

The history blog explains in detail

38、 List several magic methods and briefly introduce their uses

__init__: Initialize object
__new__: Create objects
__str__: Returns the description of the instance object
__dict__: If it is a class to call , Represents all class properties and methods in the statistics class ; If it is an object to call , The statistics are instance properties
__del__: Methods to delete object execution
__next__: Generator object to call , Keep returning data from the generator

39、d=" sdf fg ", Remove the first space

d=" sdf fg "
e=d.strip(' ')
print(e)

40、sort Sorting and sorted The difference of sorting

sort: Sort the original list , Only the list can be sorted

f=[1,4,6,3,2,4]
f.sort()
print(f)

[1, 2, 3, 4, 4, 6]

f1=(1,4,6,3,2,4)
f1.sort()
print(f1)

An error is reported when sorting tuples
Traceback (most recent call last):
File “D:\log\ceshi_log\face_1.py”, line 249, in
f1.sort()
AttributeError: ‘tuple’ object has no attribute ‘sort’

sorted: Sort the objects that can be iterated , After sorting, new iteratable objects are generated ( list )

f1=(1,4,6,3,2,4)
g=sorted(f1)
print(g,id(g))
print(f1,id(f1))

Execution results
[1, 2, 3, 4, 4, 6] 1646645367488
(1, 4, 6, 3, 2, 4) 1646643170272

41、 Use lambda Functions are sorted from small to large

f=[1,2,4,6,3,-6,5,7,-1]
f1=sorted(f,key=lambda x:x)
print(f1)

Don't use lambda Function to sort the data from small to large

f=[1,2,4,6,3,-6,5,7,-1]
f1=sorted(f)
print(f1)

Don't use lambda Function sorts data from large to small

f=[1,2,4,6,3,-6,5,7,-1]
f1=sorted(f,reverse=True)
print(f1)

42、 Use lambda Function pair list Sort foo=[-5,8,0,4,9,-4,-20,-2,8,2,-4], Positive numbers go from small to large , Negative numbers go from big to small

foo=[-5,8,0,4,9,-4,-20,-2,8,2,-4]
foo1=sorted(foo,key=lambda x:(x<0,abs(x)))
print(foo1)

[0, 2, 4, 8, 8, 9, -2, -4, -4, -5, -20]

43、 Sorting of list nested dictionaries

foo=[{
'name':'zs','age':18},
{
'name':'li','age':24},
{
'name':'ww','age':25},]
Sort by name
foo1=sorted(foo,key=lambda x:x['name'])
print(foo1)
Sort by annual collar
foo2=sorted(foo,key=lambda x:x['age'],reverse=True)
print(foo2)

[{‘name’: ‘li’, ‘age’: 24}, {‘name’: ‘ww’, ‘age’: 25}, {‘name’: ‘zs’, ‘age’: 18}]
[{‘name’: ‘ww’, ‘age’: 25}, {‘name’: ‘li’, ‘age’: 24}, {‘name’: ‘zs’, ‘age’: 18}]

44、 List nested tuple sort , Sort Letters and numbers separately

foo1=[('zs',19),('ls',18),('ww',20)]
foo2=sorted(foo1,key=lambda x:x[0])
print(foo2)
foo3=sorted(foo1,key=lambda x:x[1])
print(foo3)

[(‘ls’, 18), (‘ww’, 20), (‘zs’, 19)]
[(‘ls’, 18), (‘zs’, 19), (‘ww’, 20)]

45、 List nesting, list sorting , What if the annual income figures are the same ?

foo2=[['zs',19],['ls',18],['ww',20]]
a=sorted(foo2,key=lambda x:x[0])
b=sorted(foo2,key=lambda x:(x[1],x[0])) # The same numbers are arranged alphabetically
print(a)
print(b)

[[‘ls’, 18], [‘ww’, 20], [‘zs’, 19]]
[[‘ls’, 18], [‘zs’, 19], [‘ww’, 20]]

46、 Sort dictionaries by key

Method 1 :

dict1={
"name":"zs","city":"beijing","tel":1243124}
dict1_1=sorted(dict1.items(),key=lambda x:x)
print(dict1_1) # [('city', 'beijing'), ('name', 'zs'), ('tel', 1243124)]
new_dict={
}
for i in dict1_1:
new_dict[i[0]]=i[1]
print(new_dict)

{‘city’: ‘beijing’, ‘name’: ‘zs’, ‘tel’: 1243124}

Method 2 :

dict1={
"name":"zs","city":"beijing","tel":1243124}
dict1_1=list(zip(dict1.keys(),dict1.values()))
print(dict1_1)
dict1_2=sorted(dict1_1,key=lambda x:x[0])
new_dict={
i[0]:i[1] for i in dict1_2}
print(new_dict)

47、 Sort by string length

dt=["name1","zs","city","beijing","tel"]
dt1=sorted(dt,key=lambda x:len(x))
print(dt1)

[‘zs’, ‘tel’, ‘city’, ‘name1’, ‘beijing’]

48、 Sum recursively

dt=["name1","zs","city","beijing","tel"]
dt1=sorted(dt,key=lambda x:len(x))
print(dt1)
def func_sum(number):
if number>=1:
sum=number+func_sum(number-1)
else:
sum=0
return sum
print(func_sum(6))

21

49、 seek n The factorial


def func_sum(number):
if number==1:
return 1
else:
sum=number*func_sum(number-1)
return sum
print(func_sum(7))

5040

50、 use 2 There are three ways to get rid of the blanks

 Method 1:
st=" re rt ty"
st1=st.replace(' ','')
print(st1)
Method 2:
st2=st.split(' ')
print(st2) #['', 're', 'rt', 'ty']
st3=''.join(st2)
print(st3)

rertty
rertty


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved