Python: uporabite ukaze donosa - kako deluje
Če programirate s programom Python, ste verjetno naleteli na ukaze pridelka in generatorje. Ta praktični nasvet vam pokaže, kako ga lahko uporabljate.
Python: Uporabite ukaze donosa - kako deluje
Če ustvarite seznam s "list = [1, 2, 3]", lahko elemente posamezno izpeljete z ukazi, kot je "za i na seznamu" ↲ "print (i)".
- Seznam lahko ustvarite tudi z ukazom "list = [x * x za x v območju (3)]". Tu je "seznam" nadomestljiv. Praktična stvar iterables je, da lahko vse elemente oddajate tako pogosto, kot želite. Vendar se vsi podatki vedno shranijo trajno, kar je lahko velika ovira za velike količine podatkov.
- Generatorji so podobni iterable, vendar jih je mogoče zagnati samo enkrat, tako da podatkov ne shranijo trajno. Namesto tega se elementi izračunajo med delovanjem.
- Na primer, lahko z ukazom "testgenerator = (x * x za x v območju (3))" določite generator in elemente podate s klasičnim za zanko. Lahko pa uporabite tudi ukaz "next (testgenerator)". Vendar se lahko to ponovi samo enkrat.
- Načeloma lahko generator določite kot klasično funkcijo, vendar se namesto izjave o vračanju uporablja izjava o donosu. Kadar koli generator po zagonu pride do izjave o donosu, ga izvrši in začne nov zagon. Za razliko od izjave o vračilu generator zapomni položaj in nadaljuje z naslednjo izjavo o donosu.
- Na primer, definirajte generator z ukazom "def abc ():" ↲ "donos (" A ")" ↲ "donos (" B ")" ↲ "donos (" C ")".
- Če zdaj večkrat zapored izvajate "x = abc ()" in "naslednji (x)", se izpišejo črke A, B in C.
Več vadnic za programiranje najdete na naši strani teme programskega jezika Python. Tam vam na primer pokažemo, kako lahko preprosto programirate GUI s Python-om.