python程序设计基础(六)
今天讲述列表(list)推导式。
上次简单解释列表推导式的定义以及实例,下面深入了解推导式。其语法格式为 [表达式 for 迭代变量 in可迭代对象 [if 条件表达式]],其中可迭代对象指存储了元素的一个容器对象,且容器中的元素可以通过__iter__( )方法或__getitem__( )方法访问。包括列表、元组、字典、字符串。
下面通过例子说明。
01
一次循环
一次循环,x依次在range(10)这一范围内取值,并满足条件x > 5。
02
两次循环
两次循环,可以理解为x变量在某一确定值的情况下,y变量在范围内遍历取值,x为外层循环,y为内层循环。
03
三次循环
三次循环道理一致。x,y,z三个变量,层次依次递增。可以理解为在开始时,x,y确定的情况下z取值,y变化,z取值;x变化,y取值,z取值,层层递进。
04
拓展
针对需求不一致,灵活使用列表推导式。比如,实现5次列举x在0到3之间并以列表的形式出现。
最后,列表推导式有执行顺序,从左往右,语句的层次越高。
英文翻译
Today we will talk about list comprehensions.
Last time we briefly explained the definition and examples of list comprehensions, and let’s learn more about comprehensions.
Its grammatical format is [expression for iterative variable in iterable object [if conditional expression]], where the iterable object refers to a container object that stores the elements, and the elements in the container can be through the __iter__() method or __getitem__ () Method access. Including lists, tuples, dictionaries, and strings.
The following is an example to illustrate.
1. In one cycle, x takes values ?in the range (10) in turn, and satisfies the condition x> 5.
2. Two loops can be understood as when the x variable is at a certain value, the y variable traverses the value within the range, x is the outer loop, and y is the inner loop.
The three cycles are the same. The three variables x, y, and z increase in order. It can be understood that at the beginning, when x and y are determined, z takes the value, y changes, and z takes the value; x changes, y takes the value, and z takes the value, progressively.
3. For inconsistent requirements, use list comprehensions flexibly. For example, implement 5 times to enumerate x between 0 and 3 and qualify as a list.
Finally, the list comprehension has the order of execution, from left to right, the higher the level of the statement。
参考资料:菜鸟教程
翻译:Google翻译
本文由LearningYard新学苑原创,部分图片文字来自网络,如有侵权请联系。