In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)05/31 Report--
This article shows you what the basic topics of python are, which are concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.
1. Why study Python?
Life is but a span? It's not worth it? Think about your original heart!
2. What are the ways to learn from Python: 1544822110?
Official website, online video, learning website, forum, Daniel's tutoring
3. Comparison between Python and other languages such as Java, PHP, C, C #, C++, etc.
(1), python code, brief introduction, clear, elegant, easy to understand
(2) High development efficiency
(3) strong expansibility
4. Briefly describe the interpretive and compiled programming languages?
Interpretive type: when a program is executed, the computer interprets the code one by one into machine language for the computer to execute
Compiling type: every statement of the source program is compiled into a machine language and saved as a binary file, so that the computer can run the program directly in the machine language with high speed.
5. The types and characteristics of Python interpreter?
Cpython,IPython,Jpython,pypy,Ironpython
Python is an interpreter language. If the code wants to run, it must be executed through the interpreter. Python has a variety of interpreters, which are developed based on different languages. Each interpreter has different characteristics, but it can run Python code normally. Here are five commonly used Python interpreters:
CPython: when you download and install Python2.7 from the official Python website, you get an official version of the solution directly.
Interpreter: Cpython, this interpreter is developed in C language, so it is called CPython. Running python under a named line starts the CPython interpreter. CPython is the most widely used Python interpreter.
IPython:IPython is an interactive interpreter based on CPython, that is, IPython is only on the interactive side
It has been enhanced, but the function of executing Python code is exactly the same as that of CPython, just like many domestic browsers have a different appearance, but the kernel actually calls IE.
PyPy:PyPy is another Python interpreter whose goal is execution speed. PyPy uses JIT technology.
The Python generation is compiled dynamically, so the execution speed of Python code can be significantly improved.
Jython:Jython is a Python interpreter running on the Java platform, which can directly compile Python code into Java bytecode for execution.
IronPython:IronPython is similar to Jython, except that IronPython is a Python interpreter running on Microsoft's .net platform.
You can compile Python code directly into .net bytecode.
In the interpreter of Python, CPython is widely used. For the compilation of Python, the above interpreter can be used.
In addition to compiling, skilled developers can also write their own Python interpreter to execute Python code according to their own needs, which is very convenient!
6. The relationship between bits and bytes?
One byte = 8 bits
7. The relationship between b, B, KB, MB and GB?
1B (bytes) = 8b (bits)
1KB = 1024B
1MB = 1024KB
1GB = 1024MB
8. Please list at least 5 PEP8 specifications
(1) indentation: 4 indents at each level. Continuous line crossing should use parentheses or curly braces or use hanging indentation.
(2), code length constraint
Number of rows and columns: PEP8 stipulates a maximum of 79 columns. If splicing url is easy to exceed the limit of a function: no more than 30 lines; intuitively, it is enough to display a function in its entirety and a screen without dragging a class up or down: no more than 200 lines of code, no more than 10 methods per module: no more than 500 lines
(3), import
Do not reference multiple libraries in an import sentence
(4) naming convention
(5), comments
In general, wrong comments are better than no comments at all. So when a piece of code changes, the first thing to do is to change the comments!
9. Implement the following conversion through code:
Answer: convert binary to decimal: v = "0b1111011"
Print (int ('0b1111011)) decimal to binary: v = 18print (bin (18)) octal to decimal: v = "011" print (int (' 011)) decimal to octal: v = 30print (oct (30)) hexadecimal to decimal: v = "0x12" print (int ('0x12) decimal to hexadecimal: v = 87print (hex (87))
10. Write a function to convert the IP address to an integer.
For example, the conversion rules for 10.3.9.12 are:
10 000010103 000000119 0000100112 00001100
Then put the above binaries together to calculate the decimal result: 00001010 00000011 00001001 00001100 =?
Answer:
Def func (x): lis = x.strip (). Split ('.') li = [bin (int (I)) for i in lis] li2 = [i.replace ('0baked, (10-len (I)) *' 0') for i in li] return int ('.join (li2), 2) ret = func (' 10.3.9.12') print (ret)
11. The maximum number of layers of python recursion?
Generally speaking, the default maximum recursive depth of computers is about 1000, and the maximum recursive depth of python is about 4000.
The performance of the machine is related. This number is not a fixed number and can be tested in the following way.
Import sysprint (sys.getrecursionlimit ()) print (sys.setrecursionlimit (10000))
12. Seek results:
V1 = 1 or 3-> 1
V2 = 1 and 3-> 3
V3 = 0 and 2 and 1-> 0
V4 = 0 and 2 or 1-> 1
V5 = 0 and 2 or 1 or 4 Murmuri-> 1
V6 = 0 or Flase and 1-> False
13. The difference between ascii, unicode, utf-8 and gbk?
ASCII code: uses one byte code, so its range is basically only English letters, numbers and some special symbols, only 256characters.
Unicode: can represent all the bytes in the world
GBK: is only used to encode Chinese characters, GBK full name "Chinese character internal code extension specification", using double-byte coding.
UTF-8: is a variable length character encoding for Unicode, also known as universal code.
14. What is the difference between bytecode and machine code?
Machine code: is the computer CPU directly read and run machine instructions, running the fastest, but very obscure
Bytecode: a binary code (file) that is an intermediate state (intermediate code). It needs to be translated by a literal translator before it can become machine code.
15. Ternary operation rules and application scenarios?
Rule: the result when if determines that the condition else is false
`Application scenario: when assigning variables, you can directly add judgment, and then assign values`
16. List the difference between Python2 and Python3?
1. Default code: 2mi-> ascii,3-- > utf-8
2, the difference between print: print in python2 is a statement, no matter what you want to output, just put it after the print keyword. In python3, print () is a function
Like other functions, print () requires that you pass it what you want to output as an argument.
3. The difference of input:
Python2 has two global functions that are used on the command line to request user input. The first is called input (), which waits for the user to enter a python expression (and then returns the result). The second one is called raw_input (), which returns whatever the user types. Python3 replaced them with input.
4. Strings: there are two string types in python2: Unicode strings and non-Unicode strings. There is only one type in Python3: Unicode strings.
5. Xrange ()
In python2, there are two ways to get a range of numbers: range (), return a list, and xrange (), return an iterator. In python3, range () returns an iterator and xrange () no longer exists.
17. Implement numerical exchange with one line of code:
A = 1b = 2
Answer: a = 1
B = 2a _ r _ b = b _ r _ a
18. What is the difference between int and long in Python3 and Python2?
Python2 has int and long types for non-floating point preparation. Int type is the largest
The value cannot exceed sys.maxint, and this maximum value is platform-dependent.
Long integers can be defined by appending an L to the end of the number, which is obviously larger than the range of numbers represented by the int type. In python3
There is only one integer type, int, which in most cases is similar to the long integer in python2.
19. What's the difference between xrange and range?
In python2, there are two ways to get a range of numbers: range (), return a list, and xrange (), return an iterator.
In python3, range () returns an iterator and xrange () no longer exists.
20. File operation: what is the difference between xreadlines and readlines?
Readlines returns a list,xreadlines method returns a generator
21. List the Boolean value as the common value of False?
0, [], (), {},', False, None
22, string, list, tuple, dictionary each commonly used 5 methods?
String: repleace,strip,split,reverse,upper,lower,join.
List: append,pop,insert,remove,sort,count,index.
Tuple: index,count,__len__ (), _ _ dir__ ()
Dictionary: get,keys,values,pop,popitems,clear,update,items.
23. Lambda expression format and application scenarios?
Expression format: lambda is followed by one or more parameters, followed by a colon, followed by an expression. There is a parameter before the colon and a return value after the colon. For example: lambda x: 2x
Application scenarios: often used in conjunction with some built-in functions, such as map (), filter (), sorted (), reduce (), etc.
24. What is the role of pass?
1. Empty statement do nothing
2. Ensure the integrity of the format
3. Ensure semantic integrity
25. Arg and * kwarg function?
The universal parameter solves the problem that the function parameter is not fixed.
* arg: converts the position parameter to tuple
* * kwarg: converts keyword parameters to dict
26. What's the difference between is and =?
Is: determines whether memory addresses are equal
=: judge whether the values are equal
27. Briefly describe the deep and shallow copies of Python and the application scenarios?
Copy (): shallow copy, shallow copy refers to copying only the first layer of data in the data set
Deepcopy (): deep copy, deep copy refers to all layers of copying the data set
28. Python garbage collection mechanism?
Python adopts two strategies: citation counting mechanism, mark-clear mechanism and generational collection (intergenerational recovery, generational recycling).
Counting mechanism
Python's GC module mainly uses reference counting to track and collect garbage. On the basis of reference counting, you can also solve the problem of circular references that may be generated by container objects through "mark-clear". Through generation-by-generation recycling, space is exchanged for time to further improve the efficiency of garbage collection.
Mark-clear:
The emergence of tag-cleanup breaks circular references, that is, it focuses only on the shortcomings of objects that may produce circular references: the additional operations caused by this mechanism are proportional to the blocks of memory that need to be reclaimed.
Intergenerational recovery
Principle: all memory blocks in the system are divided into different sets according to their survival time, each set becomes a "generation", and the frequency of garbage collection decreases with the increase of the survival time of the "generation". In other words, the longer the object lives, the less likely it is to be garbage, and the frequency of garbage collection should be reduced. So how to measure this survival time: usually measured by several garbage collection actions, if an object goes through more garbage collection, it can be concluded that the longer the object survives.
29. Mutable and immutable types of python?
Immutable types (numbers, strings, tuples, immutable sets)
Variable types (lists, dictionaries, variable collections)
30. Seek results:
V = dict.fromkeys (['K1BQ K2'], [])
V ['K1'] .append (666)
Print (v)
V ['K1'] = 777
Print (v)
Answer: {'K1BZ: [666],' K2BZ: [666]} {'K1mm: [666]} {' K1mm: [666]} parsing: there is a pit when the default parameter of formkeys () is a variable data type.
31. Seek results:
Def num (): return [lambda x: iTunx for i in range (4)] print ([m (2) for m in num ()]) answer: [6, 6, 6] parse: the essence of the problem lies in the attribute lookup rule in python, LEGB (local,enclousing,global,bulitin). In the above example, I is in the enclousing of the closure, while the closure of Python is late binding, which means that the value of the variable used in the closure It is queried when the internal function is called, so: [lambda x: iComplex for i in range (4)] prints out a list of four memory addresses, and the I in each memory address is not defined in this memory, but through the I value in the closure scope. When the execution of the for loop ends, the value of I is equal to 3, so when you execute [m (2) for m in num ()]. The I value in each memory address is equal to 3, and when x is equal to 2, the printed result is 6, resulting in the result [6, 6, 6].
32. List common built-in functions?
Map,filter,zip,len,bin,oct,hex,int,float,bool,sum,min,max,str,list,tuple,dict,range,next,hash,help,id.
33. The role of filter, map and reduce?
Filter (function,iterable) filter function
Map (function,iterable) cyclic function
Reduce (function, iterable) cumulative function
34, one line of code to achieve 9: 9 multiplication table.
Lis = ['% s%% s% (iGrainjMagol ij) for i in range (1Magne10) for j in range (iMagin10)]
35. How to install a third-party module? And which third-party modules have been used?
Pip3 imstall module name
Django,Matplotlib,Tornado,PyGame
36. List at least 8 commonly used modules. Which ones are there?
Os,sys,time,random,re,hashlib,logging,json,pickle....
37. The difference between match and search of re?
Match: matches from the beginning of the string, which must start with this
Search: check from the beginning. If you find a match, return the result.
38. What is regular greedy matching?
Regular expressions tend to match the maximum length.
39. Seek results:
A. [I% 2 for i in range (10)] = = > [0BZ]
B. (I% 2 for i in range (10)) = = > returns the memory address of a generator
40. Seek results:
A. 1 or 2 = > 1
B. 1 and 2 = > 2
C. 1
< (2==2)======>False
D. 1
< 2 == 2======>Ture
41. What are the pitfalls in def func (a memery b = [])?
Def func (a _ b = []):
B.append (a) print (b)
The second default argument to the function is a list, and a list is instantiated when executed for the first time
The second execution is stored with the address instantiated at the time of the first execution, and each subsequent instantiation is
42. How to realize the transformation of "1meme 2jin3" into "1pyrrhenol 2pyrmol 3']?
A = "1, 2, 2, 3"
Li = a.split (',')
43. How to turn [1] into [1] and [2] into [1].
Li = ['1, 2, 2, 3, 3]
Lis = list (map (lambda x:int (x) li)
44. Comparison: the difference between a = [1, 2, 3] and b = [(1), (2), (3)] and b = [(1,), (2,), (3,)]?
A = [1, 1, 2, 3] normal list
B = [(1), (2), (3)] although each element of the list is parenthesized, when there is only one element in parentheses and there is no comma, its data type is the data type of the element itself
B = [(1,), (2,), (3,)] the element types in the list are all tuple types.
45. How to generate it with one line of code [1, 4, 9, 16, 25, 36, 49, 64, 81100]?
Li = [Xerox for x in range (1JI 11)]
46. One line of code to delete duplicate values in the list?
Li = [1,1,1,23,3,4,4]
New_li = list (set (li))
New_li.sort (key=li.index)
47. How to set a global variable in a function?
Use python's built-in syntax globals global variable
48. What is the function of logging module? And application scenarios?
The role of the logging module:
1. Program debugging
2. Understand the operation of the software program and whether it is normal
3. Fault analysis and problem location of software program.
Application scenario: website operation and maintenance work, program real-time monitoring
49. Please use code short answer to implement stack.
Def Stack (object):
Def _ _ init__ (self): self.stack = [] def push (self,value): # self.stack.append (value) def pop (self): # out-of-stack if self.stack:self.stack.pop () else:raise LookupError ('stack is emptiness') def is_empty (self): # check whether stack is empty reture bool (self.stack) def top (self): # take out the latest value return self.stack in stack [- 1]
50. which kinds of string formats are commonly used?
1. S d
2. Format formatted output
3. Print (f 'content {variable name}')
51. Briefly describe generators, iterators, iterable objects and application scenarios?
Generator: in Python, the mechanism of calculating while looping, called generator (generator)
Through the value of next (), two forms of expression: 1, change the [] of list generation to () 2, and the application scenario of function with yield keyword: optimize code and save memory.
Iterator: is a way to access collection elements. The iterator implements both _ _ iter__ and _ _ next__ methods.
Iterable object: as long as the object that implements the _ _ iter__ method is iterable
52. Use Python to realize a binary search function.
Lis = [0, 1, 3, 4, 5, 6, 7, 9, 10, 11]
Def two_find (x, lis, start=0, end=None):
If end= = None:end = len (lis)-1num = (end-start) / / 2 + startif end > start:if lis [num] > x:return two_find (x, lis, start=start, end=num) elif lis [num]
< x:return two_find(x, lis, start=num + 1, end=end)elif lis[num] == x:return numelif lis[end] == x:return endelse:return None print(two_find(17, lis)) 53、谈谈你对闭包的理解? 在一个外函数中定义了一个内函数,内函数里运用了外函数的临时变量,并且外函数的返回值是内函数的引用。这样就构成了一个闭包。 一般情况下,在我们认知当中,如果一个函数结束,函数的内部所有东西都会释放掉,还给内存,局部变量都会消失。 但是闭包是一种特殊情况,如果外函数在结束的时候发现有自己的临时变量将来会在内部函数中用到,就把这个临时变量绑定给了内部函数,然后自己再结束。 54、os和sys模块的作用? os模块负责程序与操作系统的交互,提供了访问操作系统底层的接口; sys模块负责程序与python解释器的交互,提供了一系列的函数和变量,用于操控python的运行时环境。 55、如何生成一个随机数? import random def rdm(n): lis = []for i in range(n): n = random.randint(1,9)lis.append(str(n))s = ''.join(lis)return int(s) 56、如何使用python删除一个文件? import os os.remove(r'path') 57、谈谈你对面向对象的理解? 面向对象的程序设计的核心是对象(上帝式思维),要理解对象为何物,必须把自己当成上帝,上帝眼里世间存在的万物皆为对象, 不存在的也可以创造出来。对象是特征和技能的结合,其中特征和技能分别对应对象的数据属性和方法属性。 优点是:解决了程序的扩展性。对某一个对象单独修改,会立刻反映到整个体系中,如对游戏中一个人物参数的特征和技能修改都很容易。 缺点:可控性差,无法向面向过程的程序设计流水线式的可以很精准的预测问题的处理流程与结果, 面向对象的程序一旦开始就由对象之间的交互解决问题,即便是上帝也无法预测最终结果。 应用场景:需求经常变化的软件,一般需求的变化都集中在用户层,互联网应用,企业内部软件,游戏等都是面向对象的程序设计大显身手的好地方。 58、Python面向对象中的继承有什么特点? 1:在继承中基类的构造(__init__()方法)不会被自动调用,它需要在其派生类的构造中亲自专门调用。 2:在调用基类的方法时,需要加上基类的类名前缀,且需要带上self参数变量。 区别于在类中调用普通函数时并不需要带上self参数 3:Python总是首先查找对应类型的方法,如果它不能在派生类中找到对应的方法,它才开始到基类中逐个查找。 (先在本类中查找调用的方法,找不到才去基类中找)。 59、面向对象深度优先和广度优先是什么? Python的类可以继承多个类,那么其寻找类方法的方式有两种: 当类是经典类时(主要在python2版本中的没有主动继承object的类),多继承情况下,会按照深度优先方式查找当类是新式类时(python3版本中的所有类和python2中主动继承object的类),多继承情况下,会按照广度优先方式查找简单点说就是:经典类是纵向查找,新式类是横向查找 60、面向对象中super的作用? 1、super在面向对象继承类中代指父类,书写方法super(类名,self).属性或者方法或super().属性或者方法 2、super方法可以增加类之间调用的灵活性,当父类名发生变化时不必修改 3、super方法在类的多继承时可以简化代码,避免代码冗余 4、super机制里可以保证公共父类仅被执行一次,执行的顺序遵循MRO,广度优先查询方法 61、是否使用过functools中的函数?其作用是什么? functools用于高阶函数:指那些作用于函数或者返回其他函数的函数。通常情况下,只要是 可以被当做函数调用的对象就是这个模块的目标。 62、列举面向对象中带双下划线的特殊方法,如:new、init __new__:构造方法,创建一个对象,实例化时第一个被执行,返回一个创建好的对象及__init__(self)的self, 只有继承了object的类才会有这个方法 __init__:初始化方法,__init__在__new__的基础上完成一些其它初始化的动作,__init__没有返回值 63、如何判断是函数还是方法? 函数和方法都封装了一些独立的功能,如果在类中定义的函数那就是方法(对象或者类名点方法名调用), 否则就是函数(函数名()直接调用) 64、静态方法和类方法区别? 静态方法:是既不是用类中的属性又不使用对象中的属性,由类或者对象调用的方法,依赖python装饰器@staticmethod来实现 类方法:只使用类中的静态变量,一般都是由类调用,依赖python装饰器@classmethod来实现 65、列举面向对象中的特殊成员以及应用场景? __call__:对象的构造方法,对象加上(),可以触发这个类的__call__方法。 __len__:内置函数的len函数是依赖类中的__len__方法 __eq__:判断值是否相等的时候依赖__eq__方法 __hash__:判断hash值是否相等的时候依赖__hash__方法(拓展:set的去重机制其实就是根据__hash__和__eq__方法实现的) __str__:和str() print() %s 都是息息相关的,返回值一定是字符串类型 __repr__:和 repr() %r都是息息相关的,在没有__str__方法时,__repr__可以完全取代__str__。 del 析构方法,对应着一个对象的删除之前执行的内容 66、1、2、3、4、5 能组成多少个互不相同且无重复的三位数 count = 0 for i in range(1,6): for j in range(1,6):for k in range(1,6):if (i != j) and (i != k) and (j != k):count += 1if count % 6:print(f'{i}{j}{k}', end='|')else:print(f'{i}{j}{k}') print(count) 67、什么是反射?以及应用场景? 定义:通过用字符串数据类型的变量名来访问这个变量的值,在python面向对象中的反射,通过字符串的形式操作对象相关的属性或方法. 应用场景:用于处理通过用户输入,文件读取,或者网络传输所得到的字符串形式的指令来完成对应的操作 68、metaclass作用?以及应用场景? metaclass,直译为元类,简单的解释就是:当我们定义了类以后,就可以根据这个类创建出实例, 所以:先定义类,然后创建实例。但是如果我们想创建出类呢?那就必须根据metaclass创建出类, 所以:先定义metaclass,然后创建类。换句话说,你可以把类看成是metaclass创建出来的"实例" 69、用尽量多的方法实现单例模式。 1、基于__new__()方法 class Person:def __new__(cls, *args, **kwargs):if not hasattr(cls,cls._instance):# cls._instance = object.__new__(cls)cls._instance = super().__new__(cls)return cls._instance 2、基于模块导入方式,现在一个py文件中写好一个类,实例化一个对象。以后用这个类直接导入这个模块就是单例模式。 3、基于装饰器方法实现 def singleton(cls, *args, **kwargs):instance_dic = {}def inner(*args, **kwargs):if cls not in instance_dic:instance_dic['cls'] = cls(*args, **kwargs)return instance_dic['cls']return inner@singletonclass Person:pass 70、装饰器的写法以及应用场景。 装饰器的写法: def wrapper(func):def inner(*args,**kwargs):'被装饰之前的操作'ret = func(*args,**kwargs)'被装饰之后的操作'return retreturn inner 装饰器的应用场景: 比如注册登录、插入日志,性能测试,事务处理,缓存等等场景 71、异常处理写法以及如何主动跑出异常(应用场景) 异常处理的常规写法: try:执行的主体函数except Exception as e:print(str(e))主动抛出异常:raise TypeError('出现了不可思议的异常')#TypeError可以是任意的错误类型 72、什么是面向对象的mro MRO(Method Resolution Order 方法解析顺序)是面向对象中用于查询类的多继承的继承顺序的方法,它是基于算法来实现的,不同的算法实现的MRO的顺序不同 73、isinstance作用以及应用场景? isinstance作用是来判断一个对象是否是一个已知的类型 74、写代码并实现: Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1] 代码实现 def func(li,target): try:for i in range(0,len(li)):num = target-li[i]if num in li:return [i,li.index(num)]except:print('li类型为数组类型,内的元素需是整型,target也为整型,请检查')else:return None 75、json序列化时,可以处理的数据类型有哪些?如何定制支持datetime类型? 1、可以处理的数据类型是 string、int、list、tuple、dict、bool、null 2、定制支持datetime类型 --------------------------官方文档的memo----------------------------------------------- >> > import json > > class ComplexEncoder (json.JSONEncoder):... Def default (self, obj):... If isinstance (obj, complex):... Return [obj.real, obj.imag]... Return json.JSONEncoder.default (self, obj). > dumps (2 + 1J, cls=ComplexEncoder)'[2.0,1.0]'> > ComplexEncoder (). Encode (2 + 1J)'[2.0,1.0]'> list (ComplexEncoder (). Iterencode (2 + 1J)) ['[', '2.0,' 1.0,']] import jsonimport datetimeret = datetime.datetime.now () class CJsonEncoder (json.JSONEncoder): def default (self, obj): if isinstance (obj) Datetime.date): return obj.strftime ('% Y-%m-%d% HGV% MVD% S') else:return json.JSONEncoder.default (self, obj) print (json.dumps (ret,cls=CJsonEncoder))
76. When serializing json, Chinese will be converted to unicode by default. What if you want to keep Chinese?
When serializing, change the default parameter ensure_ascii in json.dumps to False, and you can keep it in Chinese.
Json.dumps (obj,ensure_ascii=False)
77. What are assertions? Application scenario?
Assert condition, 'Custom error prompt (optional)' example: assert 1 = = 0Magi 'this is a low-level error'
Contract design is a classic application of assertions, and in a correct program, all pre-and post-conditions will be dealt with.
78. Use the code implementation to view all the files in the enumerated directory.
Method 1: recursive processing
Import osurl = ritual C:\ Users\ Mr.Wang\ PycharmProjects\ untitled\ previous paragraph Learning 'def check_file (url,li = []): if os.path.isdir (url): file_list = os.listdir (url) for ret in file_list:base_url = os.path.join (url,ret) if os.path.isfile (base_url): li.append (ret) else: check_file (base_url) return lielse:return os.path.basename (url)
Method 2: thought processing of stack
Import osurl = rust C:\ Users\ Mr.Wang\ PycharmProjects\ untitled\ python basic 'lis = [url] while lis:url = lis.pop () ret_list = os.listdir (url) for name in ret_list:abs_path = os.path.join (url,name) if os.path.isdir (abs_path): lis.append (abs_path) else:print (name)
79. Briefly describe the keywords yield and yield from.
Yield is a keyword similar to return, except that this function returns a generator when you call this function.
The code inside the function is not executed immediately, this function just returns a generator object when you iterate with for
Only the code in the function executes
The main function of yield from is to open a two-way channel and connect the outermost caller to the innermost child generator.
In this way, the two can send and produce values directly, and they can also pass in exceptions directly without having to add a lot of boilerplate code to handle exceptions in the middle of the co-program.
With this structure, collaborative processes can delegate responsibilities in ways that were previously impossible.
80. code to realize six-digit random verification code
Import randoms =''for i in range (6): num = random.randint (0prime9) alpha1 = chr (random.randint (65Power90)) alpha2 = chr (random.randint (97122)) ret = random.choice ([num,alpha1,alpha2]) s + = str (ret) print (s)
81. The code realizes the function of randomly sending red packets.
Import randomdef red_packge (money,num): li = random.sample (range (1 lemon money100), num-1) li.extend ([0] Money*100]) li.sort () return [(Li [index + 1]-li [index]) / 100 for index in range (num)] ret = red_packge (100pr 10) print (ret)-Generator version-import randomdef red_packge (money) Num): li = random.sample (range (1gramme moneyboy 100), num-1) li.extend ([0rect Moneyhorse 100]) li.sort () for index in range (num): yield (Li [index + 1]-li [index]) / 100ret = red_packge (100jin10) print (ret)
82. Please list the member methods of the python list as much as possible, and give the answer to the list operation:
(1) a = [1,2,3,4,5], a [:: 2] =? A [- 2:] =? A [:: 2] = [1jue 3jue 5], a [- 2:] = [4je 5] (2) one line of code realizes the summation of the even position elements in list an after adding 3? Sum ([item3 for i in a [:: 2]]) (3) disrupt the order of the elements of list a, sort a to get list b, and then construct a dictionary d with an and b in the order of elements. Import randomrandom.shuffle (a) b=a.sort () d = {} for i in range (len (a)): d [a [I]] = b [I]
83. Python introspection
Introspection is that a program written in an object-oriented language can know the type of object when it is running. That is, the type of object that can be obtained when the program is running. Such as type (), dir (), getattr (), hasattr (), isinstance ().
84. How does Python manage memory?
From three aspects, the reference counting mechanism of one object, the garbage collection mechanism and the memory pool mechanism.
I. reference counting mechanism of objects
Python uses reference counting internally to keep track of objects in memory, and all objects have reference counts.
Increase in reference count:
1, an object is assigned a new name
2, put it in a container (such as a list, tuple, or dictionary)
Cases in which the reference count decreases:
1. Destroy the alias display of the object using the de statement
2, the reference is out of scope or reassigned
The sys.getrefcount () function can get the current reference count of an object
In most cases, the citation count is much larger than you might guess. For immutable data, such as numbers and strings, the interpreter shares memory in different parts of the program to save memory.
II. Garbage collection
1. When an object's reference count returns to 00:00, it will be disposed of by the garbage collection mechanism.
2. When two objects an and b refer to each other, the del statement reduces the reference count of an and b and destroys the names used to reference the underlying objects. However, because each object contains an application to other objects, the reference count does not return to zero and the object is not destroyed. (resulting in a memory leak). To solve this problem, the interpreter periodically executes a loop detector to search for loops of inaccessible objects and delete them.
III. Memory pool mechanism
Python provides a garbage collection mechanism for memory, but it stores unused memory in a memory pool instead of returning it to the operating system.
(1) the mechanism of Pymalloc. In order to accelerate the execution efficiency of Python, Python introduces a memory pool mechanism to manage the allocation and release of small chunks of memory.
2all objects less than 256bytes in Python use the allocator implemented by pymalloc, while the large objects use the system's malloc.
3. For Python objects, such as integers, floating-point numbers, and List, each has its own independent private memory pool, and their memory pools are not shared between objects. That is, if you allocate and release a large number of integers, the memory used to cache those integers can no longer be allocated to floating-point numbers.
85. Introduce the usage and function of except?
Try... Except... Except... Else...
-- executes the statement under try. If an exception is thrown, the execution process skips to the resolve statement. Attempt execution for each except branch order, and execute the corresponding statement if the exception thrown matches the exception group in the except. If none of the except matches, the exception is passed to the next highest-level try code that invokes this code.
-- if the statement under try executes normally, the else block code is executed. If an exception occurs, it will not be executed
If there is a finally statement, it will always be executed eventually.
86. How to query and replace a text string with Python?
You can use the sub () function or subn () function in the re module to query and replace, which is more powerful than replace!
Format: sub (replacement, string [, count=0]) (replacement is the text to be replaced, string is the text to be replaced, and count is an optional parameter, which refers to the maximum number of replacements)
Import rep=re.compile ("blue | white | red") print (p.sub ('colour','blue socks and red shoes')) print (p.sub (' colour','blue socks and red shoes',count=1))
The subn () method performs the same effect as sub (), but it returns a two-dimensional array, including the new string after replacement and the total number of substitutions
Is there a tool that can help find the bug of python and do static code analysis?
PyChecker is a static analysis tool for python code, which can help find the bug of python code and warn about the complexity and format of the code.
Pylint is another tool for codingstandard checking
Most of the time, if you study with books and unsystematic video sites, you will find that there is no goal, and you don't know what you can achieve after learning a lot. To have a clear vocational study plan, you will encounter a lot of problems in the learning process. You can come to our python to learn-Qmurmurn-[1544822110], basic, advanced. Friends will communicate in it, share some learning methods and small details that need to be paid attention to, and talk about some practical cases of the project on time every day. The above are the basic topics of python. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.