gpt4 book ai didi

python - 在 Python 的 for 循环中使用多个变量

转载 作者:行者123 更新时间:2023-11-28 20:01:05 37 4
gpt4 key购买 nike

我试图更深入地了解 for 如何在 Python 中针对不同的数据类型进行循环。使用 for 循环遍历数组的最简单方法是

for i in range(len(array)):
do_something(array[i])

我也知道我可以

for i in array:
do_something(i)

我想知道这是做什么的

for i, j in range(len(array)):
# What is i and j here?

for i, j in array:
# What is i and j in this case?

如果我尝试将同样的想法用于 dictionaries 或 tuples 会发生什么?

最佳答案

最简单最好的方法是第二种,不是第一种!

for i in array:
do_something(i)

永远不要这样做,它会不必要地使代码复杂化:

for i in range(len(array)):
do_something(array[i])

如果你出于某种原因需要数组中的索引(通常你不需要),那么这样做:

for i, element in enumerate(array):
print("working with index", i)
do_something(element)

这只是一个错误,当您尝试将一个整数解包为两个名称时,您将得到 TypeError: 'int' object is not iterable:

for i, j in range(len(array)):
# What is i and j here?

这个可能有效,假设数组是“二维”的:

for i, j in array:
# What is i and j in this case?

二维数组的一个例子是成对的列表:

>>> for i, j in [(0, 1), ('a', 'b')]:
... print('i:', i, 'j:', j)
...
i: 0 j: 1
i: a j: b

注意: ['these', 'structures'] 在 Python 中称为列表,而不是数组。

关于python - 在 Python 的 for 循环中使用多个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51933830/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com