Python: używaj poleceń fed - jak to działa
Jeśli programujesz w Pythonie, prawdopodobnie natknąłeś się na polecenia wydajności i generatory. Ta praktyczna wskazówka pokazuje, jak z niego korzystać.
Python: Używaj poleceń fed - jak to działa
Jeśli utworzysz listę za pomocą „list = [1, 2, 3]”, elementy mogą być wyprowadzane indywidualnie za pomocą poleceń takich jak „for i in list” ↲ „print (i)”.
- Możesz także utworzyć listę za pomocą polecenia „list = [x * x dla xw zakresie (3)]”. Tutaj „lista” jest iterowalna. Praktyczną rzeczą w iterabach jest to, że możesz wyświetlać wszystkie elementy tak często, jak chcesz. Jednak wszystkie dane są zawsze zapisywane na stałe, co może być przeszkodą w przypadku dużych ilości danych.
- Generatory są podobne do iterowalnych, ale można je uruchomić tylko raz, więc nie przechowują danych na stałe. Elementy są raczej obliczane podczas pracy.
- Na przykład można zdefiniować generator za pomocą polecenia „testgenerator = (x * x dla xw zakresie (3))” i wyświetlać elementy za pomocą klasycznej pętli for. Możesz też użyć polecenia „next (testgenerator)”. Można to jednak powtórzyć tylko raz.
- Zasadniczo można zdefiniować generator jako funkcję klasyczną, ale zamiast instrukcji return używana jest instrukcja return. Za każdym razem, gdy generator dotrze do instrukcji wydajności po uruchomieniu, wykonuje ją i rozpoczyna nowy przebieg. W przeciwieństwie do instrukcji return, generator zapamiętuje pozycję i kontynuuje pracę z kolejną instrukcją return.
- Na przykład zdefiniuj generator za pomocą polecenia „def abc ():„ ↲ ”wydajność („ A ”)„ ↲ ”wydajność („ B ”)„ ↲ ”wydajność („ C ”)”.
- Jeśli teraz wykonasz „x = abc ()” raz i „next (x)” kilka razy z rzędu, wypisane zostaną litery A, B i C.
Więcej samouczków programowania można znaleźć na naszej stronie tematu języka programowania Python. Tam pokazujemy na przykład, jak możesz łatwo zaprogramować GUI za pomocą Pythona.