Python: käytä tuottokomentoja - miten se toimii
Jos ohjelmoit Pythonilla, olet todennäköisesti kompastellut tuottokomentoja ja generaattoreita. Tämä käytännöllinen vinkki osoittaa, kuinka voit käyttää sitä.
Python: Käytä tuottokomentoja - miten se toimii
Jos luot luettelon luettelolla "lista = [1, 2, 3]", elementit voidaan tulostaa erikseen komennoilla, kuten "luettelon i: lle" print "tulosta (i)".
- Voit myös luoda luettelon komennolla "list = [x * x x alueella x (3)]". Tässä "luettelo" on toistettava. Toistettavissa oleva käytännöllinen asia on, että kaikki elementit voidaan tulostaa niin usein kuin haluat. Kaikki tiedot tallennetaan kuitenkin aina pysyvästi, mikä voi estää suuria tietomääriä.
- Generaattorit ovat samanlaisia kuin toistettavissa olevat, mutta ne voidaan suorittaa vain kerran, joten ne eivät tallenna tietoja pysyvästi. Pikemminkin elementit lasketaan käytön aikana.
- Voit esimerkiksi määrittää generaattorin komennolla "testigeneraattori = (x * x x: lle alueella (3))" ja antaa elementtien ulostulon käyttää silmukan klassikkoa. Vaihtoehtoisesti voit käyttää myös "seuraava (testigeneraattori)" -komentoa. Tämä voi kuitenkin toistua vain kerran.
- Periaatteessa voit määrittää generaattorin kuten klassinen funktio, mutta tuottolausetta käytetään palautuslausunnon sijasta. Aina kun generaattori saapuu tuottoilmoitukseen ajon jälkeen, se suorittaa sen ja aloittaa uuden ajon. Toisin kuin palautuslausunto, generaattori muistaa sijainnin ja jatkaa seuraavalla tuottoilmoituksella.
- Määritä esimerkiksi generaattori komennolla "def abc ():" ↲ "saanto (" A ")" ↲ "saanto (" B ")" ↲ "saanto (" C ")".
- Jos suoritat nyt "x = abc ()" kerran ja "seuraava (x)" useita kertoja peräkkäin, kirjaimet A, B ja C tulostetaan.
Löydät lisää ohjelmointiohjeita Python-ohjelmointikielen aiheisivulta. Siellä me esimerkiksi osoitamme, kuinka voit helposti ohjelmoida graafisen käyttöliittymän Pythonilla itse.