


Cara yang elegan dan mudah untuk menggunakan Senarai Python: Pemahaman Senarai
You might think List Comprehension is an advanced concept. However, it can simplify your code with just one line in tricky situations. It's time to understand how it works. I will explain it at a beginner level with examples.
What Exactly is List Comprehension?
You often see the notation l2 = [x+1 for x in l]. It's said to be the same as this:
l2 = [] for x in l: x = x + 1 l2.append(x)
For both cases, if we start with l = [10, 100, 1000], l2 will be:
[11, 101, 1001]
The first syntax is what we call list comprehension.
You may prefer the usual for loop, but by the end of this article, I promise you’ll be confident using list comprehension!
In addition, let's check the detailed official definition from the documentation https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
Let's break it down more. List comprehension is just a different way to write code that is shorter and easier to make a new list. The result of list comprehension is a list, which is why we assign it to a list.
Let's go over the second part of the definition, which discusses common examples. This should be done using specific examples.
1.
fast_foods = ["Burger", "Pizza", "Tacos", "Fried Chicken", "Hot Dog"] uppercase_fast_foods = [food.upper() for food in fast_foods]
After this, uppercase_fast_foods will be:
['BURGER', 'PIZZA', 'TACOS', 'FRIED CHICKEN', 'HOT DOG']
We use the upper() function to change each food item in our list to uppercase. As a result, all items are now in uppercase. This is how we 'make new lists where each element is the result of some operations applied to each member of another sequence or iterable.'
2.
fast_foods = ["Burger", "Pizza", "Tacos", "Fried Chicken", "Hot Dog"] foods_with_space = [food for food in fast_foods if " " in food]
After this, foods_with_space will be:
['Fried Chicken', 'Hot Dog']
The line of code above retrieves the items from the list that contain a whitespace character. This is how we 'make new lists where each element is the result of some operations applied to each member of another sequence or iterable.'
Examples of List Comprehension
I’ve used list comprehensions in many problems because whenever I encountered too many for-loops, I thought, 'No problem, I’ll just simplify them.' Turns out, it’s the same logic, just cleaner! ?
Without further ado, here are some of the most relevant examples I’ve come up with:
1. Modify each element of the list
foods = ["Burger", "Fries", "Fried Chicken", "Hot Dog", "Pizza"] foods_with_version = [food + ' - 2024' for food in foods] print(foods_with_version)
Output:
['Burger - 2024', 'Fries - 2024', 'Fried Chicken - 2024', 'Hot Dog - 2024', 'Pizza - 2024']
In this example, we take a list of food items and add '- 2024' to each one. We use list comprehension to quickly create a new list with these updated names.
2. Make a sublist from a list based on a condition
foods = ["Burger", "Fried Chicken", "Hot Dog", "Fries", "Pizza"] long_foods = [food for food in foods if len(food) > 7] print(long_foods)
Output:
['Fried Chicken']`
In this example, we create a list of food items and filter out the ones that have more than 7 characters. We use list comprehension with a condition to achieve this.
3. Use the range function with list comprehension to create a list
x = [i for i in range(10, 20, 2)] print(x)
Output:
[10, 12, 14, 16, 18]
In this example, we create a list of numbers ranging from 10 to 18 using list comprehension with range().
4. Apply list comprehension to a string
input_string = "hello world" marked_vowels = ['*' if char in 'aeiouAEIOU' else char for char in input_string] print(marked_vowels)
Output:
['h', '*', 'l', 'l', '*', ' ', 'w', 'o', 'r', 'l', 'd']
In this last example, we take a string and mark its vowels with an asterisk (*). We use list comprehension to create a new list based on the original string.
Conclusion
Throughout this article, I’ve covered all the basic insights about list comprehensions, from the definition to various examples that explain them further. I hope everything is clear, and you feel more motivated to incorporate list comprehensions into your Python code from now on!
Atas ialah kandungan terperinci Cara yang elegan dan mudah untuk menggunakan Senarai Python: Pemahaman Senarai. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Anda boleh mempelajari konsep pengaturcaraan asas dan kemahiran Python dalam masa 2 jam. 1. Belajar Pembolehubah dan Jenis Data, 2.

Python digunakan secara meluas dalam bidang pembangunan web, sains data, pembelajaran mesin, automasi dan skrip. 1) Dalam pembangunan web, kerangka Django dan Flask memudahkan proses pembangunan. 2) Dalam bidang sains data dan pembelajaran mesin, numpy, panda, scikit-learn dan perpustakaan tensorflow memberikan sokongan yang kuat. 3) Dari segi automasi dan skrip, Python sesuai untuk tugas -tugas seperti ujian automatik dan pengurusan sistem.

Anda boleh mempelajari asas -asas Python dalam masa dua jam. 1. Belajar pembolehubah dan jenis data, 2. Struktur kawalan induk seperti jika pernyataan dan gelung, 3 memahami definisi dan penggunaan fungsi. Ini akan membantu anda mula menulis program python mudah.

Bagaimana Mengajar Asas Pengaturcaraan Pemula Komputer Dalam masa 10 jam? Sekiranya anda hanya mempunyai 10 jam untuk mengajar pemula komputer beberapa pengetahuan pengaturcaraan, apa yang akan anda pilih untuk mengajar ...

Cara mengelakkan dikesan semasa menggunakan fiddlerevery di mana untuk bacaan lelaki-dalam-pertengahan apabila anda menggunakan fiddlerevery di mana ...

Memuatkan Fail Pickle di Python 3.6 Kesalahan Laporan Alam Sekitar: ModulenotFoundError: Nomodulenamed ...

Bagaimana untuk menyelesaikan masalah segmentasi kata Jieba dalam analisis komen tempat yang indah? Semasa kami mengadakan komen dan analisis tempat yang indah, kami sering menggunakan alat segmentasi perkataan jieba untuk memproses teks ...

Bagaimana cara menggunakan ungkapan biasa untuk memadankan tag tertutup pertama dan berhenti? Semasa berurusan dengan HTML atau bahasa markup lain, ungkapan biasa sering diperlukan untuk ...


Alat AI Hot

Undresser.AI Undress
Apl berkuasa AI untuk mencipta foto bogel yang realistik

AI Clothes Remover
Alat AI dalam talian untuk mengeluarkan pakaian daripada foto.

Undress AI Tool
Gambar buka pakaian secara percuma

Clothoff.io
Penyingkiran pakaian AI

AI Hentai Generator
Menjana ai hentai secara percuma.

Artikel Panas

Alat panas

EditPlus versi Cina retak
Saiz kecil, penyerlahan sintaks, tidak menyokong fungsi gesaan kod

SublimeText3 Linux versi baharu
SublimeText3 Linux versi terkini

Versi Mac WebStorm
Alat pembangunan JavaScript yang berguna

Hantar Studio 13.0.1
Persekitaran pembangunan bersepadu PHP yang berkuasa

Muat turun versi mac editor Atom
Editor sumber terbuka yang paling popular