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

100000 people cant understand these Python problems, and more than 90% of learners understand them

編輯:Python

This article selects the world's second largest same-sex dating website StackOverflow Most praised in the world 10 A question , The total number of likes exceeded 5 ten thousand , Considering a lot of white whores , There are at least 10 Ten thousand people are interested in these problems !

So many people like it , Explain two questions :

1. These questions are very common , When programming, we often encounter

2. These questions are not simple , Otherwise you don't have to go to the forum

10 A question , See how many you can ?

  • Yield What is the key word ?
  • ifname== 'main’ What does it do ?
  • Python Is there a ternary operator ?
  • Python Of metaclasses What does it do ?
  • If there is no exception, check whether the file exists ?
  • How to combine two dictionaries in one sentence ?
  • Python How to call external commands , For example, start. QQ?
  • How to create a multi-layer folder safely ?
  • How to access subscripts in loops ?
  • staticmethod and classmethod The difference between ?

this 10 A question , Some are complicated , Some are simple . How many do you know ? Leave a comment in the comments section .

I was going to explain 10 A question , But because of the space , This article covers only one of the most frequently asked questions , Subsequent articles may cover a number of issues .

Now let's focus on the first question :

yield What is the key word ?

The problem is all Python Top of the list of problems :

  • 1. Yes 10000 Many people like the question , I have the same question .
  • 2. Among them, Gao Zan replied that 15000 More like .
  • 3. There are more than 2 hundred 40 Wan's view .

Details of the question ?

Yield What is the key word ?

Consider the following code :

def _get_child_candidates(self, distance, min_dist, max_dist):
if self._leftchild and distance - max_dist < self._median:
yield self._leftchild
if self._rightchild and distance + max_dist >= self._median:
yield self._rightchild

This is the calling code :

result, candidates = [], [self]
while candidates:
node = candidates.pop()
distance = node._get_dist(obj)
if distance <= max_dist and distance >= min_dist:
result.extend(node._values)
candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))
return result

When _get_child_candidates When called , What happened? ? Returned a list Do you ? It's still an element ? Will it be tuned over and over again ? When do subsequent calls stop ?

Looking a little confused ? You can continue to look at the solution , And then come back to the question .

The highest praise answers (15000 How wonderful )

To understand yield, To understand first generators, To understand generators To understand first iterable( Iterable ).

Iterables

When you create 1 individual list, You can read it one by one , It's called iteration :

>>> mylist = [1, 2, 3]
>>> for i in mylist:
... print(i)
1
2
3

above mylist It's a iterable( Can be iterated ). When you use a list derivation , You create a list , That's one iterable:

>>> mylist = [x*x for x in range(3)]
>>> for i in mylist:
... print(i)
0
1
4

So you can use for…in… What syntax traverses is iterable:list, str, file wait

these iterable It is useful to , You can cycle through them . But all of their values are in memory . If your list There is 10 100 million strings , To create this list It's going to be slow , And it takes up a lot of memory , So we need Genertor.

Generators

Generator yes iterable, Can be recycled . But it's not the same as above , It can only be cycled once . It doesn't keep all the values in memory , They dynamically generate the values of the elements in the loop .

>>> mygenerator = (x*x for x in range(3))
>>> for i in mygenerator:
... print(i)
0
1
4

This generator is almost the same as the list derivation , The only difference is the use of parentheses (), Not brackets []. but , You can't use it twice for i in mygenerator, Because the generator can only be cycled once : They calculate 0x0, Return results , I don't keep it myself , Next time you call it , He calculated 1x1, And so on .

Yield

Yields It's a key word , It can be understood as and return equally , The difference is that it returns a generator.


>>> def createGenerator():
... mylist = range(3)
... for i in mylist:
... yield i*i
...
>>> mygenerator = createGenerator() # create a generator
>>> print(mygenerator) # mygenerator is an object!
<generator object createGenerator at 0xb7555c34>
>>> for i in mygenerator:
... print(i)
0
1
4

The above example creates range, Has taken up memory , But the square doesn't take up . This example is not very good , This is the original author's example , There should be a better example in my video .

First , because yield The existence of , When you call the function above , The code is not executed , Instead of returning a Generator.

And then there's the key :

  • When for The first time the loop calls generator When , It's going to start from scratch , until yield key word , Returns the first value , That is to say 0.
  • Then remember which line of code to execute , That is to say yield The location of .
  • The next time for The loop calls it again , It is from yield Continue on the next line of , Until we meet again yield, Return to next value , That is to say 1.
  • This process is repeated all the time , until generator There's no more content in . In this example range The numbers in are used up .

Now let's look at the first question :

This is a tree traversal algorithm , Find the eligible nodes in the tree . Detailed Chinese comments are added to the code .

Generator:

# This function returns a generator (Generator), This is a binary tree node Methods in objects
def _get_child_candidates(self, distance, min_dist, max_dist):
# If there's a left child , And the distance meets the requirements , Back to the left child , And then pause here
if self._leftchild and distance - max_dist < self._median:
yield self._leftchild
# If there's a right child , And the distance meets the requirements , Back to right child , And then pause here
if self._rightchild and distance + max_dist >= self._median:
yield self._rightchild
# If it's done here , It means that there are no qualified left and right children , The generator is empty , It's the end of the iteration .

Caller:

# Create an empty list , And the current object node
result, candidates = list(), [self]
# loop , In the beginning, it was just myself
while candidates:
# Pop up the last node
node = candidates.pop()
# get obj The distance between the object and the target node
distance = node._get_dist(obj)
# If distance ok, Write to the result list
if distance <= max_dist and distance >= min_dist:
result.extend(node._values)
# Add your own child node to the candidates in , So the cycle will continue , Until all the nodes in the tree are traversed
candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))
return result

About Python Technology reserve

Learn from good examples Python Whether it's employment or sideline, it's good to make money , But learn to Python Still have a learning plan . Finally, let's share a complete set of Python Learning materials , For those who want to learn Python Let's have a little help !

One 、Python Learning routes in all directions

Python All directions are Python Sort out the common technical points , Form a summary of knowledge points in various fields , The use of it is , You can find the corresponding learning resources according to the above knowledge points , Make sure you learn more comprehensively .

Two 、 Learning software

If a worker wants to do a good job, he must sharpen his tools first . Study Python Common development software is here , It saves you a lot of time .

3、 ... and 、 Getting started video

When we were watching videos to learn , You can't just move your eyes and brain without hands , A more scientific way to learn is to use them after understanding , At this time, the hand training program is very suitable .

Four 、 Practical cases

Optical theory is useless , Learn to knock together , Do it , Can you apply what you have learned to practice , At this time, we can make some practical cases to learn .

5、 ... and 、 Interview information

We learn Python Must be to find a well paid job , The following interview questions are from Ali 、 tencent 、 The latest interview materials of big Internet companies such as byte , And the leader Ali gave an authoritative answer , After brushing this set of interview materials, I believe everyone can find a satisfactory job .


This full version of Python A full set of learning materials has been uploaded CSDN, Friends can scan the bottom of wechat if necessary CSDN The official two-dimensional code is free 【 Guarantee 100% free


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