백엔드 개발 파이썬 튜토리얼 Python 목록을 사용하는 우아하고 간단한 방법: 목록 이해

Python 목록을 사용하는 우아하고 간단한 방법: 목록 이해

Sep 28, 2024 am 08:10 AM

An elegant and simple way to use Python Lists: List Comprehensions

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!

위 내용은 Python 목록을 사용하는 우아하고 간단한 방법: 목록 이해의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

뜨거운 기사 태그

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

HTML을 구문 분석하기 위해 아름다운 수프를 어떻게 사용합니까? HTML을 구문 분석하기 위해 아름다운 수프를 어떻게 사용합니까? Mar 10, 2025 pm 06:54 PM

HTML을 구문 분석하기 위해 아름다운 수프를 어떻게 사용합니까?

파이썬의 이미지 필터링 파이썬의 이미지 필터링 Mar 03, 2025 am 09:44 AM

파이썬의 이미지 필터링

파이썬에서 파일을 다운로드하는 방법 파이썬에서 파일을 다운로드하는 방법 Mar 01, 2025 am 10:03 AM

파이썬에서 파일을 다운로드하는 방법

Python을 사용하여 텍스트 파일의 ZIPF 배포를 찾는 방법 Python을 사용하여 텍스트 파일의 ZIPF 배포를 찾는 방법 Mar 05, 2025 am 09:58 AM

Python을 사용하여 텍스트 파일의 ZIPF 배포를 찾는 방법

플라스크에 소개 : 연락처 페이지 추가 플라스크에 소개 : 연락처 페이지 추가 Feb 28, 2025 am 10:03 AM

플라스크에 소개 : 연락처 페이지 추가

Python을 사용하여 PDF 문서를 사용하는 방법 Python을 사용하여 PDF 문서를 사용하는 방법 Mar 02, 2025 am 09:54 AM

Python을 사용하여 PDF 문서를 사용하는 방법

Django 응용 프로그램에서 Redis를 사용하여 캐시하는 방법 Django 응용 프로그램에서 Redis를 사용하여 캐시하는 방법 Mar 02, 2025 am 10:10 AM

Django 응용 프로그램에서 Redis를 사용하여 캐시하는 방법

Tensorflow 또는 Pytorch로 딥 러닝을 수행하는 방법은 무엇입니까? Tensorflow 또는 Pytorch로 딥 러닝을 수행하는 방법은 무엇입니까? Mar 10, 2025 pm 06:52 PM

Tensorflow 또는 Pytorch로 딥 러닝을 수행하는 방법은 무엇입니까?

See all articles