第213页 | Learning Python | 阅读 ‧ 电子书库

同步阅读进度,多语言翻译,过滤屏幕蓝光,评论分享,更多完整功能,更好读书体验,试试 阅读 ‧ 电子书库

List Iteration and Comprehensions

More generally, lists respond to all the sequence operations we used on strings in the prior chapter, including iteration tools:

>>> 3 in [1, 2, 3]                           # Membership
True
>>> for x in [1, 2, 3]:
...     print(x, end=' ')                    # Iteration
...
1 2 3

We will talk more formally about for iteration and the range built-ins in Chapter 13, because they are related to statement syntax. In short, for loops step through items in any sequence from left to right, executing one or more statements for each item.

The last items in Table 8-1, list comprehensions and map calls, are covered in more detail in Chapter 14 and expanded on in Chapter 20. Their basic operation is straightforward, though—as introduced in Chapter 4, list comprehensions are a way to build a new list by applying an expression to each item in a sequence, and are close relatives to for loops:

>>> res = [c * 4 for c in 'SPAM']            # List comprehensions
>>> res
['SSSS', 'PPPP', 'AAAA', 'MMMM']

This expression is functionally equivalent to a for loop that builds up a list of results manually, but as we’ll learn in later chapters, list comprehensions are simpler to code and faster to run today:

>>> res = []
>>> for c in 'SPAM':                         # List comprehension equivalent
...     res.append(c * 4)
...
>>> res
['SSSS', 'PPPP', 'AAAA', 'MMMM']

As also introduced in Chapter 4, the map built-in function does similar work, but applies a function to items in a sequence and collects all the results in a new list:

>>> list(map(abs, [−1, −2, 0, 1, 2]))        # map function across sequence
[1, 2, 0, 1, 2]

Because we’re not quite ready for the full iteration story, we’ll postpone further details for now, but watch for a similar comprehension expression for dictionaries later in this chapter.

请支持我们,让我们可以支付服务器费用。
使用微信支付打赏


上一页 · 目录下一页


下载 · 书页 · 阅读 ‧ 电子书库