在 Python 的 for 循环中使用多个变量 [英] Using multiple variables in a for loop in Python

查看:169
本文介绍了在 Python 的 for 循环中使用多个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我也知道我可以

for i in array:做某事(一)

我想知道这是做什么

for i, j in range(len(array)):# 这里的 i 和 j 是什么?

对于数组中的 i, j:# 在这种情况下,i 和 j 是什么?

如果我尝试对 dictionaries 或 tuples 使用相同的想法会发生什么?

解决方案

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

for i in array:做某事(一)

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

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

如果您出于某种原因需要数组中的索引(通常您不需要),请改为这样做:

for i, enumerate(array) 中的元素:打印(使用索引",我)做某事(元素)

这只是一个错误,当你试图将一个整数解包成两个名字时,你会得到TypeError: 'int' object is not iterable:

for i, j in range(len(array)):# 这里的 i 和 j 是什么?

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

对于数组中的 i, j:# 在这种情况下,i 和 j 是什么?

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

<预><代码>>>>对于 i, j 在 [(0, 1), ('a', 'b')]:...打印('我:',我,'j:',j)...i: 0 j: 1我:a j:b

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

I am trying to get a deeper understanding to how for loops for different data types in Python. The simplest way of using a for loop an iterating over an array is as

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

I also know that I can

for i in array:
    do_something(i)

What I would like to know is what this does

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

or

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

And what happens if I try using this same idea with dictionaries or tuples?

解决方案

The simplest and best way is the second one, not the first one!

for i in array:
    do_something(i)

Never do this, it's needlessly complicating the code:

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

If you need the index in the array for some reason (usually you don't), then do this instead:

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

This is just an error, you will get TypeError: 'int' object is not iterable when trying to unpack one integer into two names:

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

This one might work, assumes the array is "two-dimensional":

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

An example of a two-dimensional array would be a list of pairs:

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

Note: ['these', 'structures'] are called lists in Python, not arrays.

这篇关于在 Python 的 for 循环中使用多个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆