Python: gunakan perintah hasil - bagaimana ia berfungsi
Sekiranya anda memprogramkan dengan Python, anda mungkin tersandung pada perintah dan penjana hasil. Petua praktikal menunjukkan anda bagaimana anda boleh menggunakannya.
Python: Gunakan perintah hasil - bagaimana ia berfungsi
Jika anda membuat senarai dengan "list = [1, 2, 3]", anda boleh mempunyai output unsur secara individu menggunakan perintah seperti "untuk senarai saya" ↲ "cetak (i)".
- Anda juga boleh membuat senarai dengan arahan "list = [x * x for x in range (3)]". Di sini "senarai" adalah iterable. Perkara praktikal mengenai lelaran adalah bahawa anda boleh mempunyai semua elemen output seberapa kerap yang anda suka. Walau bagaimanapun, semua data sentiasa disimpan secara kekal, yang boleh menjadi halangan bagi sejumlah besar data.
- Penjana adalah sama dengan leluar, tetapi ia hanya boleh dijalankan sekali, jadi mereka tidak menyimpan data secara kekal. Sebaliknya, unsur-unsur dikira semasa operasi.
- Sebagai contoh, anda boleh menentukan penjana dengan arahan "testgenerator = (x * x untuk x dalam julat (3))" dan mempunyai output unsur dengan gelung klasik. Sebagai alternatif, anda juga boleh menggunakan "next (testgenerator)" perintah. Walau bagaimanapun, ini hanya boleh sekali gus.
- Pada prinsipnya, anda boleh menentukan penjana seperti fungsi klasik, tetapi pernyataan hasil digunakan dan bukannya penyata pulangan. Setiap kali penjana tiba di pernyataan hasil selepas larian, ia melaksanakannya dan memulakan larian baru. Tidak seperti penyata pulangan, penjana mengingati kedudukan dan meneruskan pernyataan hasil seterusnya.
- Sebagai contoh, tentukan penjana dengan arahan "def abc ():" ↲ "hasil (" A ")" ↲ "hasil (" B ")" ↲ "hasil (" C ")".
- Sekiranya anda sekarang melaksanakan "x = abc ()" sekali dan "seterusnya (x)" beberapa kali berturut-turut, huruf A, B, dan C akan dikeluarkan.
Anda boleh mendapatkan lebih banyak tutorial pengaturcaraan pada halaman topik bahasa pemrograman Python kami. Di sana kami tunjukkan kepada anda, contohnya, bagaimana anda boleh memprogram GUI dengan Python dengan mudah.