如何在 Python 的 for 循环中进行计数

在 Python 中的 for 循环中计数

How to count in a for loop in Python

使用该enumerate()函数在 for 循环中计数,例如
for index, item in enumerate(my_list):该函数接受一个可迭代对象并返回一个包含元组的对象,其中第一个元素是索引,第二个元素是项目。

主程序
my_list = ['a', 'b', 'c'] # ✅ count in for loop for index, item in enumerate(my_list): print(index, item) # 👇️ # 0 a # 1 b # 2 c # --------------------------------------------- # ✅ count in for loop starting with N for count, item in enumerate(my_list, start=1): print(count, item) # 👇️ # 1 a # 2 b # 3 c # ---------------------------------------------- # ✅ manually incrementing counter in for loop counter = 0 for item in my_list: counter += 1 print(counter) print(counter) # 👉️ 3

enumerate函数接受一个可迭代对象并返回一个包含元组的
枚举对象,其中第一个元素是索引,第二个元素是项目。

我们可以直接解压索引(或计数)和for循环中的项目。

主程序
my_list = ['a', 'b', 'c'] for index, item in enumerate(my_list): print(index, item) # 👇️ # 0 a # 1 b # 2 c

enumerate函数有一个可选start参数,默认为
0.

If you need to start the count from a different number, e.g. 1, specify the
start argument in the call to enumerate().

main.py
my_list = ['a', 'b', 'c'] for count, item in enumerate(my_list, start=1): print(count, item) # 👇️ # 1 a # 2 b # 3 c

The count variable has an initial value of 1 and then gets incremented by
1 on each iteration.

Alternatively, you can manually count in the for loop.

To count in a for loop:

  1. Initialize a count variable and set it a number.
  2. Use a for loop to iterate over a sequence.
  3. On each iteration, reassign the count variable to its current value plus N.
main.py
my_list = ['a', 'b', 'c'] count = 0 for item in my_list: count += 1 print(count) print(count) # 👉️ 3

We declared a count variable and initially set it to 0.

On each iteration, we use the += operator to reassign the variable to its current value plus N.

The following 2 lines of code achieve the same result:

  • count += 1
  • count = count + 1

下面是一个使用更长的重新分配语法的示例。

主程序
my_list = ['a', 'b', 'c'] count = 0 for item in my_list: count = count + 1 print(count) print(count) # 👉️ 3

发表评论