Loops
Loops are a way to repeatedly execute some code. Here's an example:
循环
循环是重复执行某些代码的一种方式。 这是一个例子:
planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
for planet in planets:
print(planet, end=' ') # print all on same line
Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune
The
loop specifies for
- the variable name to use (in this case,
planet
) - the set of values to loop over (in this case,
planets
)
You use the word "
" to link them together.in
The object to the right of the "
" can be any object that supports iteration. Basically, if it can be thought of as a group of things, you can probably loop over it. In addition to lists, we can iterate over the elements of a tuple:in
循环指定for
- 要使用的变量名称(在本例中为
planet
) - 要循环的值集(在本例中为
planets
)
您可以使用
一词将它们链接在一起。in
in
右侧的对象可以是任何支持迭代的对象。 基本上,如果它可以被视为一组事物,那么您可能可以对其进行循环。 除了列表之外,我们还可以迭代元组的元素:
multiplicands = (2, 2, 2, 3, 3, 5)
product = 1
for mult in multiplicands:
product = product * mult
product
360
You can even loop through each character in a string:
您甚至可以循环遍历字符串中的每个字符:
s = 'steganograpHy is the practicE of conceaLing a file, message, image, or video within another fiLe, message, image, Or video.'
msg = ''
# print all the uppercase letters in s, one at a time
for char in s:
if char.isupper():
print(char, end='')
HELLO
range()
range()
is a function that returns a sequence of numbers. It turns out to be very useful for writing loops.
For example, if we want to repeat some action 5 times:
range()
“range()”是一个返回数字序列的函数。 事实证明它对于编写循环非常有用。
例如,如果我们想重复某个动作 5 次:
range()
range()
是一个返回数字序列的函数。 事实证明它对于编写循环非常有用。
例如,如果我们想重复某个动作 5 次:
for i in range(5):
print("Doing important work. i =", i)
Doing important work. i = 0
Doing important work. i = 1
Doing important work. i = 2
Doing important work. i = 3
Doing important work. i = 4
while
loops
while
The other type of loop in Python is a
loop, which iterates until some condition is met:while
while
循环
Python 中的另一种类型的循环是while
循环,它会迭代直到满足某些条件:
i = 0
while i < 10:
print(i, end=' ')
i += 1 # increase the value of i by 1
0 1 2 3 4 5 6 7 8 9
The argument of the
loop is evaluated as a boolean statement, and the loop is executed until the statement evaluates to False.while
while
循环的参数被当成布尔语句,并且循环执行,直到该语句的计算结果为 False。
List comprehensions
List comprehensions are one of Python's most beloved and unique features. The easiest way to understand them is probably to just look at a few examples:
列表推导式
列表推导式是 Python 最受欢迎且最独特的功能之一。 理解它们的最简单方法可能就是看几个例子:
squares = [n**2 for n in range(10)]
squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Here's how we would do the same thing without a list comprehension:
以下是我们在没有列表推导式的情况下如何做同样的事情:
squares = []
for n in range(10):
squares.append(n**2)
squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
We can also add an if
condition:
我们还可以添加一个if
条件:
short_planets = [planet for planet in planets if len(planet) < 6]
short_planets
['Venus', 'Earth', 'Mars']
(If you're familiar with SQL, you might think of this as being like a "WHERE" clause)
Here's an example of filtering with an if
condition and applying some transformation to the loop variable:
(如果您熟悉 SQL,您可能会认为这就像WHERE
子句)
下面是使用if
条件进行过滤的示例并对循环变量应用一些转换:
# str.upper() returns an all-caps version of a string
# str.upper() 返回字符的大写版本
loud_short_planets = [planet.upper() + '!' for planet in planets if len(planet) < 6]
loud_short_planets
['VENUS!', 'EARTH!', 'MARS!']
People usually write these on a single line, but you might find the structure clearer when it's split up over 3 lines:
人们通常将它们写在一行上,但是当它分成 3 行时,您可能会发现结构更清晰:
[
planet.upper() + '!'
for planet in planets
if len(planet) < 6
]
['VENUS!', 'EARTH!', 'MARS!']
(Continuing the SQL analogy, you could think of these three lines as SELECT, FROM, and WHERE)
The expression on the left doesn't technically have to involve the loop variable (though it'd be pretty unusual for it not to). What do you think the expression below will evaluate to? Press the 'output' button to check.
(继续 SQL 类比,您可以将这三行视为 SELECT、FROM 和 WHERE)
从技术上讲,左侧的表达式不必涉及循环变量(尽管不涉及循环变量的情况很不寻常)。 您认为下面的表达式会计算出什么结果? 按输出
按钮进行检查。
[32 for planet in planets]
[32, 32, 32, 32, 32, 32, 32, 32]
List comprehensions combined with functions like min
, max
, and sum
can lead to impressive one-line solutions for problems that would otherwise require several lines of code.
For example, compare the following two cells of code that do the same thing.
列表推导式与min
、max
和sum
等函数相结合,可以为原本需要几行代码的问题提供令人印象深刻的一行解决方案。
例如,比较执行相同操作的以下两个代码单元。
def count_negatives(nums):
"""Return the number of negative numbers in the given list.
>>> count_negatives([5, -1, -2, 0, 3])
2
"""
n_negative = 0
for num in nums:
if num < 0:
n_negative = n_negative + 1
return n_negative
Here's a solution using a list comprehension:
这是使用列表推导式的解决方案:
def count_negatives(nums):
return len([num for num in nums if num < 0])
Much better, right?
Well if all we care about is minimizing the length of our code, this third solution is better still!
好多了,对吧?
好吧,如果我们关心的只是最小化代码的长度,那么第三种解决方案更好!
def count_negatives(nums):
# Reminder: in the "booleans and conditionals" exercises, we learned about a quirk of
# Python where it calculates something like True + True + False + True to be equal to 3.
return sum([num < 0 for num in nums])
Which of these solutions is the "best" is entirely subjective. Solving a problem with less code is always nice, but it's worth keeping in mind the following lines from The Zen of Python:
Readability counts.
Explicit is better than implicit.
So, use these tools to make compact readable programs. But when you have to choose, favor code that is easy for others to understand.
这些解决方案中哪一个是最好的
完全是主观的。 用更少的代码解决问题总是好的,但值得记住 Python 之禅 中的以下几行:
可读性很重要。
显式优于隐式。
因此,使用这些工具来制作紧凑可读的程序。 但当您必须选择时,请选择易于其他人理解的代码。
Your Turn
You know what's next -- we have some fun coding challenges for you! This next set of coding problems is shorter, so try it now.
到你了
您知道接下来会发生什么 - 我们为您准备了一些 有趣的编码挑战! 下一组编码问题较短,所以现在就尝试一下。