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

Essence Python top ten B syntax

編輯:Python


Python It's a language for simple ideas , Its grammar is relatively simple , Easy to get started . however , If you look down on this Python The subtlety and depth of grammar , That would be a big mistake . This article carefully selected the best show Python Ten points of knowledge of the subtlety of grammar , And attach the detailed example code . If we can get through it in real combat 、 Flexible use , Will make the code more refined 、 Efficient , At the same time, it will greatly improve the code B grid , Make it look more sophisticated , More elegant to read .

1. for - else

what ? No if and else Is that the original match ?No, You may not know ,else It's a two boat guy ,for and else It's also a pair of , And it's legal . Top ten B grammar ,for-else It's definitely nanwuwan ! Don't believe it , Please have a look at :

>> for i in [1,2,3,4]:

print(i)
else:
print(i, ' I am a else')

1
2
3
4 I am a else
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

If in for and else Between ( Circulating body ) There is a third party if come , It won't affect for and else The relationship between . because for The level of if high ,else Another guy who clings to power , I don't care if there is if, And whether satisfaction has been performed if Conditional statement .else In the eyes of for, as long as for The smooth implementation is over ,else I'll run through it :

>>> for i in [1,2,3,4]:

if i > 2:
print(i)
else:
print(i, ' I am a else')
4 I am a else
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

that , How to break up for and else This pair of enemies ? Only when for Cyclic quilt break After the statement is interrupted , To skip else sentence :

>>> for i in [1,2,3,4]:

if i>2:
print(i)
break
else:
print(i, ' I am a else')
3
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

2. A star (*) And two stars (**)

Did you find , star (*) It's a magic symbol ! Think about it , Without it ,C What's more interesting about language ? Again , Because of it ,Python Will be so graceful 、 charming appearance and personality 、 lovingly pathetic !Python Functions support default and variable parameters , A star represents an unlimited number of single valued parameters , Two stars represent an unlimited number of key value pairs of parameters .

Let's give an example : Design a function , Returns the sum of multiple input values . Of course, we can make these input values into a list Pass to function , But this method , Far from using a star's variable parameters to be elegant :

>>> def multi_sum(*args):

s = 0
for item in args:
s += item
return s

>>> multi_sum(3,4,5)
12
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

Python Function allows fixed parameters to be used in whole or in part at the same time 、 Default parameters 、 Single value ( A star ) Variable parameters 、 Key value pair ( Two stars ) Variable parameters , It must be written in the above order .

>>> def do_something(name, age, gender=' male ', *args, **kwds):

print(' full name :%s, Age :%d, Gender :%s'%(name, age, gender))
print(args)
print(kwds)

>>> do_something('xufive', 50, ' male ', 175, 75, math=99, english=90)
full name :xufive, Age :50, Gender : male
(175, 75)
{'math': 99, 'english': 90}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

Besides , One star and two stars can also be used for lists 、 Tuples 、 Unpacking dictionary , It looks more like C Language :

>>> a = (1,2,3)

>>> print(a)
(1, 2, 3)
>>> print(*a)
1 2 3
>>> b = [1,2,3]
>>> print(b)
[1, 2, 3]
>>> print(*b)
1 2 3
>>> c = {'name':'xufive', 'age':51}
>>> print(c)
{'name': 'xufive', 'age': 51}
>>> print(*c)
name age
>>> print('name:{name}, age:{age}'.format(**c))
name:xufive, age:51
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.

3. Ternary expression

be familiar with C/C++ The programmer , First time python when , I will miss the classic ternary operator , Because I want to express the same thought , use python It seems more troublesome to write . such as :

>>> y = 5

>>> if y < 0:
print('y It's a negative number ')
else:
print('y It's a non negative number ')

y It's a non negative number
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

Actually ,python It supports ternary expressions , It's just a little weird , It's similar to what we Shandong people say . such as , Shandong people like to use inversion sentence most : Go to play , If it doesn't rain ; It's raining , Let's go to the study room . Translation into a ternary expression is :

Go to play if No rain else To study room

Let's take a look at the specific use of ternary expressions :

>>> y = 5

>>> print('y It's a negative number ' if y < 0 else 'y It's a non negative number ')
y It's a non negative number

python The ternary expression of can also be used to assign :

>>> y = 5
>>> x = -1 if y < 0 else 1
>>> x
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

4. with - as

with This word , It's not difficult to translate in English , But in Python How to translate in grammar , I really can't think of , It's basically a context management protocol . As a beginner , No need to pay attention with What are the various methods and mechanisms of , Just understand its application scenario .with The statement is suitable for some preparation in advance , Tasks that need to be dealt with afterwards , such as , File operations , You need to open the file first , File needs to be closed after operation . If not used with, File operations usually have to do this :

fp = open(r"D:\CSDN\Column\temp\mpmap.py", 'r')

try:
contents = fp.readlines()
finally:
fp.close()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

If you use with - as, Then it's much more elegant :

>>> with open(r"D:\CSDN\Column\temp\mpmap.py", 'r') as fp:

contents = fp.readlines()
  • 1.
  • 2.

5. List derivation

In all kinds of strange grammar , List derivation should be used the most frequently , The effect of code simplification is also very obvious . such as , Square the elements of the list , Usually it should be written like this ( There are other ways of writing, of course , For example, use map function ):

>>> a = [1, 2, 3, 4, 5]

>>> result = list()
>>> for i in a:
result.append(i*i)

>>> result
[1, 4, 9, 16, 25]
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

If you use list derivation , It looks much more comfortable :

>>> a = [1, 2, 3, 4, 5]

>>> result = [i*i for i in a]
>>> result
[1, 4, 9, 16, 25]
  • 1.
  • 2.
  • 3.
  • 4.

in fact , Derivations support more than lists , Dictionaries are also supported 、 aggregate 、 Tuples and so on . If you are interested , You can do your own research . I have a blog 《 a line Python What insane functions can the code achieve ?》, Here's an example , They are all implemented by list derivation .

6. Various operations of list index

Python Introduce negative integer as index of array , This is absolutely a move of "happy big and common" . think about it , stay C/C++ in , Want the last element of the array , We have to get the array length first , Subtract one and index , It seriously affects the coherence of thinking .Python The success of language , Personally, I think , Among many factors , The convenience of list operation cannot be ignored . Please have a look at :

>>> a = [0, 1, 2, 3, 4, 5]

>>> a[2:4]
[2, 3]
>>> a[3:]
[3, 4, 5]
>>> a[1:]
[1, 2, 3, 4, 5]
>>> a[:]
[0, 1, 2, 3, 4, 5]
>>> a[::2]
[0, 2, 4]
>>> a[1::2]
[1, 3, 5]
>>> a[-1]
5
>>> a[-2]
4
>>> a[1:-1]
[1, 2, 3, 4]
>>> a[::-1]
[5, 4, 3, 2, 1, 0]
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.

if , You are familiar with all these , Also often used , So the next usage , You must feel amazing :

>>> a = [0, 1, 2, 3, 4, 5]

>>> b = ['a', 'b']
>>> a[2:2] = b
>>> a
[0, 1, 'a', 'b', 2, 3, 4, 5]
>>> a[3:6] = b
>>> a
[0, 1, 'a', 'a', 'b', 4, 5]
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

7. lambda function

lambda It sounds very tall , It's actually anonymous functions ( understand js You must be familiar with anonymous functions ). What is the application scenario of anonymous function ? Use this function only where anonymous functions are defined , There is no use for , So there's no need to give it a cat or a dog . Here's an anonymous function that sums , There are two input parameters ,x and y, The body of a function is x+y, omitted return keyword .

>>> lambda x,y: x+y

<function <lambda> at 0x000001B2DE5BD598>
>>> (lambda x,y: x+y)(3,4) # Because anonymous functions don't have names , When you use it, wrap it in brackets
  • 1.
  • 2.
  • 3.

Anonymous functions are not used alone , But with other methods , Provide built-in algorithms or judging conditions for other methods . such as , Use sort function sorted When sorting multidimensional arrays or dictionaries , You can specify the collation .

>>> a = [{'name':'B', 'age':50}, {'name':'A', 'age':30}, {'name':'C', 'age':40}]

>>> sorted(a, key=lambda x:x['name']) # Sort by name
[{'name': 'A', 'age': 30}, {'name': 'B', 'age': 50}, {'name': 'C', 'age': 40}]
>>> sorted(a, key=lambda x:x['age']) # Sort by age
[{'name': 'A', 'age': 30}, {'name': 'C', 'age': 40}, {'name': 'B', 'age': 50}]
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

Let's take another example of how to square an array element , This time map function :

>>> a = [1,2,3]

>>> for item in map(lambda x:x*x, a):
print(item, end=', ')

1, 4, 9,
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

8. yield And generators and iterators

yield This word , It's hard to translate , It's no use reading a dictionary . I'll just read it as “ One loves ”, It's a foreign word . To understand yield, You have to understand generator( generator ). To understand generator, You have to know first iterator( iterator ). Ha ha ha , I'm dizzy ? Forget it , I'd better speak in vain .

Words py2 Time ,range() The return is list, But if range(10000000) Words , It will consume a lot of memory resources , therefore ,py2 Another xrange() To solve this problem .py3 Only keep xrange(), But writing range().xrange() What is returned is an iterator , It can look like list That's traversed , But it doesn't take up much memory .generator( generator ) It's a special kind of iterator , Can only be traversed once , End of traversal , It's gone . All in all , Either iterator or generator , All in order to avoid using list, To save memory . that , How to get iterators and generators ?

python Built in iteration function iter, Used to generate iterators , Usage is as follows :

>>> a = [1,2,3]

>>> a_iter = iter(a)
>>> a_iter
<list_iterator object at 0x000001B2DE434BA8>
>>> for i in a_iter:
print(i, end=', ')

1, 2, 3,
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

yield It's for building generators . such as , We're going to write a function , Return from 0 The square of all integers to a positive integer , The traditional way of writing code is like this :

>>> def get_square(n):

result = list()
for i in range(n):
result.append(pow(i,2))
return result

>>> print(get_square(5))
[0, 1, 4, 9, 16]
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

But if you calculate 1 The square of all integers within 100 million , The memory cost of this function will be very large , This is a yield Then you can do your best :

>>> def get_square(n):

for i in range(n):
yield(pow(i,2))

>>> a = get_square(5)
>>> a
<generator object get_square at 0x000001B2DE5CACF0>
>>> for i in a:
print(i, end=', ')

0, 1, 4, 9, 16,
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

If I traverse again , There will be no output .

9. Decorator

Just figured out iterators and generators , Here's another decorator ,Python Why so many devices ? You bet ,Python A lot of weapons are provided for us , Ornaments are one of the most powerful weapons . Decorators are very powerful , I'm here to try... From a needs perspective , Let's take a simple example , Explain how to use the decorator and how to make it .

If we need to define many functions , Show the run time of each function when it is running , There are many solutions . such as , You can read the time stamp before calling each function , Read the timestamps after each function , Just ask for the difference ; You can also read timestamps at the beginning and end of each function body , The last difference . however , These two methods , It's not as simple as using decorators 、 grace . The following example , It's a good demonstration of this .

>>> import time

>>> def timer(func):
def wrapper(*args,**kwds):
t0 = time.time()
func(*args,**kwds)
t1 = time.time()
print(' Time consuming %0.3f'%(t1-t0,))
return wrapper

>>> @timer
def do_something(delay):
print(' function do_something Start ')
time.sleep(delay)
print(' function do_something end ')

>>> do_something(3)
function do_something Start
function do_something end
Time consuming 3.077
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.

timer() Is the decorator function we define , Use @ Attach it to any function ( such as do_something) Before definition , It's like putting a newly defined function , As input parameter of decorator function . function do_something() function , It can be understood as execution timer(do_something) . The details are complicated , But that's not a big deviation , And it is easier to grasp the manufacture and use of decorators .

10. Use assertions wisely assert

The so-called assertion , Is to declare that the Boolean value of an expression must be true , Otherwise it will trigger AssertionError abnormal . Strictly speaking ,assert It's debugging , Not suitable for use in production environment , But this doesn't affect how we use assertions to implement certain functions , such as , Format of input parameters 、 Type verification, etc .

>>> def i_want_to_sleep(delay):

assert(isinstance(delay, (int,float))), ' Function arguments must be integers or floating-point numbers '
print(' Start sleeping ')
time.sleep(delay)
print(' I wake up ')

>>> i_want_to_sleep(1.1)
Start sleeping
I wake up
>>> i_want_to_sleep(2)
Start sleeping
I wake up
>>> i_want_to_sleep('2')
Traceback (most recent call last):
File "<pyshell#247>", line 1, in <module>
i_want_to_sleep('2')
File "<pyshell#244>", line 2, in i_want_to_sleep
assert(isinstance(delay, (int,float))), ' Function arguments must be integers or floating-point numbers '
AssertionError: Function arguments must be integers or floating-point numbers
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.




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