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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

Linux 터미널에서 Python 버전을 보려고 할 때 Linux 터미널에서 Python 버전을 볼 때 권한 문제에 대한 솔루션 ... Python을 입력하십시오 ...

이 기사에서는 HTML을 구문 분석하기 위해 파이썬 라이브러리 인 아름다운 수프를 사용하는 방법을 설명합니다. 데이터 추출, 다양한 HTML 구조 및 오류 처리 및 대안 (SEL과 같은 Find (), find_all (), select () 및 get_text ()와 같은 일반적인 방법을 자세히 설명합니다.

Python의 통계 모듈은 강력한 데이터 통계 분석 기능을 제공하여 생물 통계 및 비즈니스 분석과 같은 데이터의 전반적인 특성을 빠르게 이해할 수 있도록 도와줍니다. 데이터 포인트를 하나씩 보는 대신 평균 또는 분산과 같은 통계를보고 무시할 수있는 원래 데이터에서 트렌드와 기능을 발견하고 대형 데이터 세트를보다 쉽고 효과적으로 비교하십시오. 이 튜토리얼은 평균을 계산하고 데이터 세트의 분산 정도를 측정하는 방법을 설명합니다. 달리 명시되지 않는 한,이 모듈의 모든 함수는 단순히 평균을 합산하는 대신 평균 () 함수의 계산을 지원합니다. 부동 소수점 번호도 사용할 수 있습니다. 무작위로 가져옵니다 수입 통계 Fracti에서

이 기사는 딥 러닝을 위해 텐서 플로와 Pytorch를 비교합니다. 데이터 준비, 모델 구축, 교육, 평가 및 배포와 관련된 단계에 대해 자세히 설명합니다. 프레임 워크, 특히 계산 포도와 관련하여 주요 차이점

이 기사는 Numpy, Pandas, Matplotlib, Scikit-Learn, Tensorflow, Django, Flask 및 요청과 같은 인기있는 Python 라이브러리에 대해 설명하고 과학 컴퓨팅, 데이터 분석, 시각화, 기계 학습, 웹 개발 및 H에서의 사용에 대해 자세히 설명합니다.

이 기사는 Python 개발자가 CLIS (Command-Line Interfaces) 구축을 안내합니다. Typer, Click 및 Argparse와 같은 라이브러리를 사용하여 입력/출력 처리를 강조하고 CLI 유용성을 향상시키기 위해 사용자 친화적 인 디자인 패턴을 홍보하는 세부 정보.

Python의 Pandas 라이브러리를 사용할 때는 구조가 다른 두 데이터 프레임 사이에서 전체 열을 복사하는 방법이 일반적인 문제입니다. 두 개의 dats가 있다고 가정 해

이 기사는 프로젝트 종속성 관리 및 충돌을 피하는 데 중점을 둔 Python에서 가상 환경의 역할에 대해 설명합니다. 프로젝트 관리 개선 및 종속성 문제를 줄이는 데있어 생성, 활성화 및 이점을 자세히 설명합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

뜨거운 주제



