如何用Python一个for循环同时迭代多个变量?

2026-04-20 12:131阅读0评论SEO教程
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计403个文字,预计阅读时间需要2分钟。

如何用Python一个for循环同时迭代多个变量?

首先,熟悉一个函数zip,如下所示:+ Help on built-in function zip in module __builtin__:zip(...) zip(seq1, seq2, ...) -> list of tuples Return a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The returned list is shorter than any of the iterables if the iterables are of unequal lengths.

首先,熟悉一个函数zip,如下是使用help(zip)对zip的解释。

Help on built-in function zip in module __builtin__:

zip(...)

zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

Return a list of tuples, where each tuple contains the i-th element
from each of the argument sequences. The returned list is truncated
in length to the length of the shortest argument sequence.

看一个实例:

如何用Python一个for循环同时迭代多个变量?

x = [1, 2, 3] y = [-1, -2, -3] # y = [i * -1 for i in x] zip(x, y)

zip的结果如下:

[(1, -1), (2, -2), (3, -3)]

zip([seql, ...])接受一系列可迭代对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些tuples组成的list(列表)。

进入正题:如何使用一个for循环同时循环多个变量呢?使用tuple。如下,同时循环i和j变量。

for (i, j) in [(1, 2), (2, 3), (4, 5)]: print(i, j)

输出结果如下:

(1, 2) (2, 3) (4, 5)

所以我们如果要将x和y中的元素分别相加,则可以使用如下代码:

for (i, j) in zip(x, y): print(i + j)

输出结果:

0 0 0

以上这篇Python中一个for循环循环多个变量的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持易盾网络。

标签:示例

本文共计403个文字,预计阅读时间需要2分钟。

如何用Python一个for循环同时迭代多个变量?

首先,熟悉一个函数zip,如下所示:+ Help on built-in function zip in module __builtin__:zip(...) zip(seq1, seq2, ...) -> list of tuples Return a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The returned list is shorter than any of the iterables if the iterables are of unequal lengths.

首先,熟悉一个函数zip,如下是使用help(zip)对zip的解释。

Help on built-in function zip in module __builtin__:

zip(...)

zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

Return a list of tuples, where each tuple contains the i-th element
from each of the argument sequences. The returned list is truncated
in length to the length of the shortest argument sequence.

看一个实例:

如何用Python一个for循环同时迭代多个变量?

x = [1, 2, 3] y = [-1, -2, -3] # y = [i * -1 for i in x] zip(x, y)

zip的结果如下:

[(1, -1), (2, -2), (3, -3)]

zip([seql, ...])接受一系列可迭代对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些tuples组成的list(列表)。

进入正题:如何使用一个for循环同时循环多个变量呢?使用tuple。如下,同时循环i和j变量。

for (i, j) in [(1, 2), (2, 3), (4, 5)]: print(i, j)

输出结果如下:

(1, 2) (2, 3) (4, 5)

所以我们如果要将x和y中的元素分别相加,则可以使用如下代码:

for (i, j) in zip(x, y): print(i + j)

输出结果:

0 0 0

以上这篇Python中一个for循环循环多个变量的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持易盾网络。

标签:示例