g=(i for i in range(4))
for i in [1,10]:
g=(i+j for j in g)
print(list(g))
may I ask why the result is: [20,21,22,23]
instead of: [11mem12121314]?
g=(i for i in range(4))
for i in [1,10]:
g=(i+j for j in g)
print(list(g))
may I ask why the result is: [20,21,22,23]
instead of: [11mem12121314]?
generator is that it does not execute immediately, but remembers the 'mode of production' until it is called.
in your example:
g = (i for i in range (4))-sharp at this time, if called by list, g will be called, but it will not be called, but in the generator
the following loop:
for i in [1jue 10]:
g=(i+j for j in g)
does not mean that when the first cycle I is 1, g should be [1 br 2]. In fact, g is not called and all is not executed, just remember that the value of the generator is
the second cycle, I is 10, which is also not executed, but just remember the value of the variable I in the loop when it is called and executed by the print (list (g)) command. It's already 10.
so each value in the final g is executed twice in a row, that is, iExamj
, so the output of print (list (g)) is [20,21,22,23]
what's even more amazing is your code:
g = (i for i in range (4))
for i in [1Jing 10]:
g=(i+j for j in g)
for i in g:
print(i)-sharp20,41,84,171
isn't it weirder that the output is different from list (g)?
but if you change the name of the loop variable:
for k in g:
print(k)-sharp20, 21, 22, 23
the output is consistent with list (g). Why?
is also because the producer "remembers the mode of production and is not executed immediately".
in generator g, the variable I always exists and has not been released and recycled, and then using the variable I to cycle the value of gpeni will cause confusion. In the first cycle, I is still 10, so the first value is 20. At this time, the I value has been assigned to 20, so when the second cycle executes iPlus, You get 41. In the same way, when you execute I + (iExj) for the third time, I is already 41, the fourth time. So the final output is 20pc41pyrus 84171
after changing the cyclic variable I to k, the variable name is no longer repeated and the assignment is no longer confused, which is consistent with the result of list (g)
.this may be complicated to explain. The generator will execute the code only when it is needed, but another knowledge premise is needed here, that is, the variables in the deduction are temporary variables and will not affect other variables. Let's take a simple example:
x = 5
a = (x for x in range(3))
print(list(a)) -sharp [0, 1, 2]
print(x) -sharp 5
I don't remember which version of python dealt with this problem. There is no variable protection mechanism in some older versions, at least I used version 3.6. By the same token, let's take a look at this, which is closer to the title:
g=(i for i in range(4))
i = 8
print(list(g))
guess what will be printed here, which is [0,1,2,3]
. The I in the generator is protected, so it has nothing to do with the external variable I, and its value must be 0123.
look at another one:
a = 1
g=(a + i for i in range(4))
a = 5
print(list(g))
here I is protected, but a
is not. Since the value of subsequent an is 5, the generator in the print statement should be < gen 5 + 0,5 + 1,. >
.
well, we can finally talk about the code in the title. g = (i for i in range (4) in the first line of
, I is protected, so its iteration is always
) 0x3
for i in [1,10]:
g=(i+j for j in g)
the j here is also protected, and in the first loop, its value is the initial output of g. Here, I is not protected, but only binds variables to get its value when the generator generates the data.
value of g after the first loop:
<gen i+0, i+1, i+2, i+3>
in the second cycle, j is the value of production. Although iTun10
at this time, I is subsequently bound, so the value of g after the second cycle of production:
<gen i+i+0, i+i+1, i+i+2, i+i+3>
when the statement is finally printed, the value of I is the last value of the loop body (10), so the printout 20,21,22,23
by the way, upstairs:
g=(i for i in range(4))
for i in [1,10]:
g=(i+j for j in g)
for i in g:
print(i) -sharp20,41,84,171
give an explanation.
before the second loop body starts, the g generator is < gen iLoop 0, iLoop 1,., i+i+3 >
.
for i in g
indicates that the data generated from g is assigned to I. Get i+i+0
from the generator. To generate data, I have to substitute the value at this time. What is the value at this time? Yes, I is the last value (10) of the last loop body, so generate 20 and assign 20 to I;
the second loop fetches i+i+1
from the generator, where I is 20 (the last loop assigned the value, the difficulty is here), so the generation is 41, assign the value to I again;
third loop, get i+i+2
at this time the value of I is 41, so the resulting value is 84, which is assigned to I again;
. Wait
Previous: How to lock the table to ensure consistency when sequelize manipulates the table?
Next: The problem of merging javascript Multidimensional arrays according to key values
dict1 = { "system.cpu.user.pct": { "value": 12.83 }, "system.load.1": { "value": 0.33 } } dict2 = { "system": { "...
description: a regular match is given to the content of an input box, and the matching content is the product activation code. looks like this: "0C31-0B81-BB32-3094-0C31-0B81-BB32-3094 " Code: $( -sharplicenseCode ).keyup(function () { le...
for example, the known two-dimensional list [[aformab], [dpene], [f]] requires an element from each sublist to be added and lists all the combinations. The output of this question is adf,aef,bdf,bef,cdf,cef. There are many such lists, and the number of s...
I want the program to randomly issue five cards with different colors and numbers (it doesn t matter if there are occasional cards with the same number), but I find that five cards are always the same. import random suites = [ "Hearts ", "Diamonds ...
this problem works fine after I add code to the first line, but do I have to pay attention to this every time? Python novice asks ...
{% csrf_token%}, is added to the form form of html in the template. MIDDLEWARE = [ django.middleware.security.SecurityMiddleware , django.contrib.sessions.middleware.SessionMiddleware , django.middleware.common.CommonMiddleware , ...
when we use the ansible tool, the default is to use ssh for remote control. you need to generate key pairs in a way similar to ssh-keygen-t rsa , and then use the ssh-copy-id command to distribute the public key file to a remote host and enter the pas...
python replaces the content in front of the vertical bar symbol in the title, but it has been unsuccessful, for example: Chen Ning column (Chinese football fight to correct the name of Wales Uruguay for the championship, replace Chen Ning column for oth...
the article on Wechat s official account crawled through python at the backend found that the video in the article could not be played, and the video was nested in iframe, as shown in <iframe class="video_iframe" data-vidtype="2"...
as in the title, write a simple function test to generate a soup object from the URL using Python requests and BeautifulSoup, (see the example below). If you call this function directly in the main thread, everything will be fine, but if you call this f...
blog s article like function, like once + 1, use session to record the current user problem point is: if you like article 1, article 2 will indicate that it has been supported. The reason is to judge that session how to realize that articles cannot b...
1. Condition: according to whether the alias in the two lines intersect, and if so, Then merge separated by-sharp sign, where: alias 2 in alias separated by-sharp sign, data name alias 0 potato potato-sharp egg-sharp potato-sharp potato 1 potato p...
Baidu said that there is a problem with the verification method in the file var lib pgsql 9.5 data pg_hba.conf, but the reason for changing the verification method is to use the command psql-U postgres-d mydjango-p 5432-h 127.0.0.1 to log in directl...
I ve been looking for it for a long time, but I can t find it. 1. After the direct upload of web is completed, the server cannot know whether the file was uploaded successfully, who uploaded it, and the information of the file 2. Using web to dire...
currently I have a piece of code that spends most of its time on the above two sentences of data filtering in dataframe. temp_df = df [df [ "data_date "] .isin (date_list)] temp = temp_df [rule [2]] [temp_df [ "data_date "] = = d] at present, it tak...
< H2 > 1. Question: < H2 > like the title, how does the chart displayed by matplotlib.pyplot.show () in pycharm pop up to sciview,? < H2 > 2. Code: < H2 > import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib impo...
I need to install both python 2.6 and python 3.6 on my machine. Based on my query, I found that I could use pyenv to do this things, but according to an article I read, python 2 series didn t come with package management tools until python 2.7.9. The...
The question is written on the title, is there any way to be spaced by BAN, when it is applied too fast in crawlers? Or is it that there is no interval in this kind of concurrency? ...
Open a chrome browser using selenium, and open a Baidu web page. Using the send_keys () method to fill in the content in the search box, there are the following problems -sharpcoding:utf-8 from selenium import webdriver from selenium.webdriver.chrom...
the newly installed win7 system, Ann python is, the installation package setup comes out of this, which I have encountered before. I forgot how to solve it. ...