Python: izmantojiet ražas komandas - kā tas darbojas
Ja jūs programmējat ar Python, iespējams, esat nokļuvis starp ienesēšanas komandām un ģeneratoriem. Šis praktiskais padoms parāda, kā jūs to varat izmantot.
Python: izmantojiet ražas komandas - kā tas darbojas
Ja izveidojat sarakstu ar "list = [1, 2, 3]", elementus var izvadīt atsevišķi, izmantojot tādas komandas kā "i sarakstam" ↲ "print (i)".
- Jūs varat arī izveidot sarakstu ar komandu "list = [x * x x x diapazonā (3)]". Šeit "saraksts" ir atkārtojams. Praktiska lieta par iterables ir tā, ka jūs varat visus elementus izvadīt tik bieži, cik vēlaties. Tomēr visi dati vienmēr tiek saglabāti neatgriezeniski, kas var kavēt lielu datu daudzumu.
- Ģeneratori ir līdzīgi atkārtojamiem, taču tos var darbināt tikai vienu reizi, tāpēc tie datus neuzglabā pastāvīgi. Drīzāk elementi tiek aprēķināti darbības laikā.
- Piemēram, jūs varat definēt ģeneratoru ar komandu "testgenerator = (x * x x x diapazonā (3))" un norādīt, ka elementi tiek izvadīti ar klasiku cilpai. Alternatīvi, jūs varat arī izmantot komandu "nākamais (testa ģenerators)". Tomēr tas var atkārtoties tikai vienu reizi.
- Principā ģeneratoru var definēt kā klasisku funkciju, bet atgriešanās paziņojuma vietā tiek izmantots ienesīguma paziņojums. Ikreiz, kad ģenerators nonāk pēc ražas paziņojuma par ienesīgumu, tas to izpilda un sāk jaunu palaišanu. Atšķirībā no atgriešanās paziņojuma, ģenerators atceras pozīciju un turpina ar nākamo ienesīguma paziņojumu.
- Piemēram, definējiet ģeneratoru ar komandu "def abc ():" ↲ "raža (" A ")" ↲ "raža (" B ")" ↲ "raža (" C ")".
- Ja jūs tagad izpildāt "x = abc ()" vienreiz un "nākamais (x)" vairākas reizes pēc kārtas, tiks izvadīti burti A, B un C.
Plašākas programmēšanas konsultācijas varat atrast mūsu Python programmēšanas valodas tēmu lapā. Tur mēs, piemēram, parādīsim, kā jūs pats varat viegli programmēt GUI ar Python.