5、Python循环及列表推导式(List Comprehension)

For 和 while 循环以及 Python最重要的功能:列表推导式(List Comprehension)

文章目录

  • 1.循环
    • 1.1 range()
    • 1.2 `while` 循环
  • 2.列表推导式

1.循环

循环是重复执行某些代码的一种方式:

In [1]:

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 

for循环指定了以下内容:

  • 要使用的变量名(在这种情况下是 planet
  • 要循环遍历的值集合(在这种情况下是 planets

你使用 “in” 连接它们。

in” 右边的对象可以是任何支持迭代的对象。基本上,如果可以将其看作一组事物,那么你可能可以对其进行循环遍历。除了列表,我们还可以遍历元组的元素:

In [2]:

multiplicands = (2, 2, 2, 3, 3, 5)
product = 1
for mult in multiplicands:
    product = product * mult
product

Out[2]:

360

您甚至可以循环遍历字符串中的每个字符:

In [3]:

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 

你可能感兴趣的:(从零开始的Python之旅,list,windows,python)