Python Comprehensions
A Python comprehension is a distinctive way of processing data that builds a new data structure from an existing data sequence.
Python comprehensions are a powerful and concise syntax, suitable for generating lists, dictionaries, sets and generators.
When using comprehensions, pay attention to readability and keep expressions concise so as not to hurt readability and maintainability.
Python supports comprehensions for various data structures:
- List comprehensions
- Dictionary comprehensions
- Set comprehensions
- Tuple comprehensions
List comprehension
The list comprehension format is:
[表达式 for 变量 in 列表]
[out_exp_res for out_exp in input_list]
或者
[表达式 for 变量 in 列表 if 条件]
[out_exp_res for out_exp in input_list if condition]
- out_exp_res: the expression that generates list elements; it can be a function with a return value.
- for out_exp in input_list: iterates over input_list and passes out_exp into the out_exp_res expression.
- if condition: a conditional clause that filters out values that do not meet the condition.
Filter out strings of length 3 or less from a list and convert the rest to uppercase:
Example
names
=
[
'Bob'
,
'Tom'
,
'alice'
,
'Jerry'
,
'Wendy'
,
'Smith'
]
new_names
=
[
name.
upper
(
)
for
name
in
names
if
len
(
name
)
3
]
(
new_names
)
[
'ALICE'
,
'JERRY'
,
'WENDY'
,
'SMITH'
]
Compute the integers below 30 that are divisible by 3:
Example
multiples
=
[
i
for
i
in
range
(
30
)
if
i %
3
==
0
]
(
multiples
)
[
0
,
3
,
6
,
9
,
12
,
15
,
18
,
21
,
24
,
27
]
Dictionary comprehension
The basic dictionary comprehension format:
{ key_expr: value_expr for value in collection }
或
{ key_expr: value_expr for value in collection if condition }
Create a dictionary from strings and their lengths:
Example
listdemo
=
[
'Google'
,
'Runoob'
,
'Taobao'
]
Use each string in the list as a key and its length as the value to form key-value pairs
newdict
=
{
key:
len
(
key
)
for
key
in
listdemo
}
newdict
{
'Google'
:
6
,
'Runoob'
:
6
,
'Taobao'
:
6
}
Given three numbers, create a dictionary with the numbers as keys and their squares as values:
Example
dic
=
{
x: x**
2
for
x
in
(
2
,
4
,
6
)
}
dic
{
2
:
4
,
4
:
16
,
6
:
36
}
type
(
dic
)
<
class
'dict'
Set comprehension
The basic set comprehension format:
{ expression for item in Sequence }
或
{ expression for item in Sequence if conditional }
Compute the squares of the numbers 1, 2, 3:
Example
setnew
=
{
i**
2
for
i
in
(
1
,
2
,
3
)
}
setnew
{
1
,
4
,
9
}
Identify and output the letters that are not in abc:
Example
a
=
{
x
for
x
in
'abracadabra'
if
x
not
in
'abc'
}
a
{
'd'
,
'r'
}
type
(
a
)
<
class
'set'
Tuple comprehension (generator expression)
Tuple comprehensions can use range intervals, tuples, lists, dictionaries and sets to quickly generate a tuple that meets a given requirement.
The basic tuple comprehension format:
(expression for item in Sequence )
或
(expression for item in Sequence if conditional )
Tuple comprehensions work exactly like list comprehensions, except that tuple comprehensions wrap the parts in () parentheses while list comprehensions use square brackets []. Also, a tuple comprehension returns a generator object.
For example, we can use the following code to generate a tuple containing the numbers 1~9:
Example
a
=
(
x
for
x
in
range
(
1
,
10
)
)
a
<
generator
object
<
genexpr
at
0x7faf6ee20a50
What is returned is a generator object
tuple
(
a
)
Use the tuple() function to convert the generator object directly into a tuple
(
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
)