对于Python中的循环

对于循环语句 (For Loop Statements)

Python utilizes a for loop to iterate over a list of elements. Unlike C or Java, which use the for loop to change a value in steps and access something such as an array using that value.

Python利用for循环来遍历元素列表。 与C或Java不同,它们使用for循环逐步更改值并使用该值访问数组等内容。

For loops iterate over collection based data structures like lists, tuples, and dictionaries.

For循环遍历基于集合的数据结构,如列表,元组和字典。

The basic syntax is:

基本语法为:

for value in list_of_values:
  # use value inside this block

In general, you can use anything as the iterator value, where entries of the iterable can be assigned to. E.g. you can unpack tuples from a list of tuples:

通常,您可以使用任何东西作为迭代器值,可以将可迭代项的条目分配到该值。 例如,您可以从元组列表中解包元组:

list_of_tuples = [(1,2), (3,4)]

for a, b in list_of_tuples:
  print("a:", a, "b:", b)

On the other hand, you can loop over anything that is iterable. You can call a function or use a list literal.

另一方面,您可以遍历任何可迭代的对象。 您可以调用函数或使用列表文字。

for person in load_persons():
  print("The name is:", person.name)
for character in ["P", "y", "t", "h", "o", "n"]:
  print("Give me a '{}'!".format(character))

Some ways in which For loops are used:

使用For循环的一些方法:

遍历range()函数 (Iterate over the range() function)

for i in range(10):
    print(i)

Rather than being a function, range is actually an immutable sequence type. The output will contain results from lower bound i.e 0 to the upper bound i.e 10 but excluding 10.By default the lower bound or the starting index is set to zero. Output:

范围不是函数,实际上是不可变的序列类型。 输出将包含从下限即0到上限即10的结果,但不包括10。默认情况下,下限或起始索引设置为零。 输出:

>
0
1
2
3
4
5
6
7
8
9
>

Additionally, one can specify the lower bound of the sequence and even the step of the sequence by adding a second and a third parameter.

另外,可以通过添加第二个和第三个参数来指定序列的下限甚至序列的步骤。

for i in range(4,10,2): #From 4 to 9 using a step of two
    print(i)

Output:

输出:

>
4
6
8
>

xrange()函数 (xrange() function)

For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use, however you please. The only difference is that range returns a Python list object and xrange returns an xrange object. It means that xrange doesn’t actually generate a static list at run-time like range does. It creates the values as you need them with a special technique called yielding. This technique is used with a type of object known as generators.

在大多数情况下,xrange和range在功能方面完全相同。 它们都提供了一种生成整数列表供您使用的方法,但是您可以随意使用。 唯一的区别是range返回一个Python列表对象,而xrange返回一个xrange对象。 这意味着xrange在运行时实际上不会像range那样生成静态列表。 它使用称为yield的特殊技术根据需要创建值。 该技术与一种称为生成器的对象一起使用。

One more thing to add. In Python 3.x, the xrange function does not exist anymore. The range function now does what xrange does in Python 2.x

再增加一件事。 在Python 3.x中,不再存在xrange函数。 现在,范围函数可以执行xrange在Python 2.x中的功能

遍历列表或元组中的值 (Iterate over values in a list or tuple)

A = ["hello", 1, 65, "thank you", [2, 3]]
for value in A:
    print(value)

Output:

输出:

>
hello
1
65
thank you
[2, 3]
>

遍历字典中的键(也称为哈希图) (Iterate over keys in a dictionary (aka hashmap))

fruits_to_colors = {"apple": "#ff0000",
                    "lemon": "#ffff00",
                    "orange": "#ffa500"}

for key in fruits_to_colors:
    print(key, fruits_to_colors[key])

Output:

输出:

>
apple #ff0000
lemon #ffff00
orange #ffa500
>

使用zip()函数在一个循环中迭代两个相同大小的列表 (Iterate over two lists of same size in a single loop with the zip() function)

A = ["a", "b", "c"]
B = ["a", "d", "e"]

for a, b in zip(A, B):
  print a, b, a == b

Output:

输出:

>
a a True
b d False
c e False
>

遍历列表并使用enumerate()函数获取相应的索引 (Iterate over a list and get the corresponding index with the enumerate() function)

A = ["this", "is", "something", "fun"]

for index,word in enumerate(A):
    print(index, word)

Output:

输出:

>
0 this
1 is
2 something
3 fun
>

A common use case is iterating over a dictionary:

一个常见的用例是遍历字典:

for name, phonenumber in contacts.items():
  print(name, "is reachable under", phonenumber)

If you absolutely need to access the current index of your iteration, do NOT use range(len(iterable))! This is an extremely bad practice and will get you plenty of chuckles from senior Python developers. Use the built in function enumerate() instead:

如果您绝对需要访问迭代的当前索引,请不要使用range(len(iterable)) ! 这是非常糟糕的做法,会让您从高级Python开发人员那里获得很多笑声。 使用内置函数enumerate()代替:

for index, item in enumerate(shopping_basket):
  print("Item", index, "is a", item)

for / else语句 (for/else statements )

Pyhton permits you to use else with for loops, the else case is executed when none of the conditions with in the loop body was satisfied. To use the else we have to make use of break statement so that we can break out of the loop on a satsfied condition.If we do not break out then the else part will be executed.

Pyhton允许您将else与for循环一起使用,当不满足循环主体中with的条件时,将执行else情况。 要使用else,我们必须使用break语句,这样我们才能在满足条件的情况下跳出循环。如果不跳出,则将执行else部分。

week_days = ['Monday','Tuesday','Wednesday','Thursday','Friday']
today = 'Saturday'
for day in week_days:
  if day == today:
    print('today is a week day')
    break
else:
  print('today is not a week day')

In the above case the output will be today is not a week day since the break within the loop will never be executed.

在上述情况下,输出将today is not a week day因为循环内的中断将永远不会执行。

使用内联循环功能遍历列表 (Iterate over a list using inline loop function)

We could also iterate inline using python, for example if we need to uppercase all the words in a list from a list we could simply do the following:

我们还可以使用python进行内联迭代,例如,如果需要将列表中列表中的所有单词都大写,则可以简单地执行以下操作:

A = ["this", "is", "awesome", "shinning", "star"]

UPPERCASE = [word.upper() for word in A]
print (UPPERCASE)

Output:

输出:

>
['THIS', 'IS', 'AWESOME', 'SHINNING', 'STAR']
>
更多信息: (More Information:)

翻译自: https://www.freecodecamp.org/news/for-loops-in-python/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值