Comprehensions in Python

2020-07-24  本文已影响0人  游文影月志

Comprehension is a very powerful technique to make complicated things simple in Python.

This article will talk about list comprehensions, dictionary comprehensions, and set comprehensions in Python.

1. Python List Comprehension

Suppose, we want to separate the letters of the word Hello and add the letters as items of a list.

We usually use a for loop to complete it:

a = []

for letter in 'Hello':
    a.append(letter)

print(a)  # => ['H', 'e', 'l', 'l', 'o']

List comprehension is an elegant way to define and create lists based on existing lists.

上一篇 下一篇

猜你喜欢

热点阅读