在 Python 的 for 循环中使用多个变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51933830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using multiple variables in a for loop in Python
提问by Ely Fialkoff
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
Python 中不同数据类型的循环方式。使用 for 循环迭代数组的最简单方法是
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 dict
ionaries or tuples
?
如果我尝试将同样的想法与dict
ionaries 或一起使用会发生什么tuples
?
回答by wim
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:
这只是一个错误,TypeError: 'int' object is not iterable
当您尝试将一个整数解包为两个名称时会得到:
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.
注意:['these', 'structures']
在 Python 中称为列表,而不是数组。
回答by modesitt
Your third loop will not work as it will throw a TypeError
for an int
not being iterable
. This is because you are trying to "unpack
" the int that is the array's index into i
, and j
which is not possible. An example of unpacking is like so:
你的第三个循环将不起作用,因为它会抛出 a TypeError
for an int
not being iterable
。这是因为您试图将unpack
作为数组索引的 int 插入到 中i
,j
这是不可能的。一个解包的例子是这样的:
tup = (1,2)
a,b = tup
where you assign a
to be the first value in the tuple
and b
to be the second. This is also useful when you may have a function
return a tuple of values and you want to unpack them immediately when calling the function. Like,
在那里您指定a
为 中的第一个值tuple
并b
指定为第二个值。当您可能有一个function
返回值的元组并且您想在调用函数时立即解压缩它们时,这也很有用。喜欢,
train_X, train_Y, validate_X, validate_Y = make_data(data)
More common loop cases that I believe you are referring to is how to iterate over an arrays items and it's index.
我相信您所指的更常见的循环案例是如何迭代数组项及其索引。
for i, e in enumerate(array):
...
and
和
for k,v in d.items():
...
when iterating over the items in a dictionary
. Furthermore, if you have two lists, l1
and l2
you can iterate over both of the contents like so
当迭代 a 中的项目时dictionary
。此外,如果您有两个列表,l1
并且l2
可以像这样迭代这两个内容
for e1, e2 in zip(l1,l2):
...
Note that this will truncate the longer list in the case of unequal lengths while iterating. Or say that you have a lists of lists where the outer lists are of length m
and the inner of length n
and you would rather iterate over the elements in the inner lits grouped together by index. This is effectively iterating over the transpose of the matrix, you can use zip to perform this operation as well.
请注意,如果迭代时长度不等,这将截断较长的列表。或者说您有一个列表列表,其中外部列表的长度为长度m
,内部的列表为长度,n
并且您宁愿迭代按索引分组在一起的内部 lits 中的元素。这有效地迭代了矩阵的转置,您也可以使用 zip 来执行此操作。
for inner_joined in zip(*matrix): # will run m times
# len(inner_joined) == m
...
回答by bruno desthuilliers
Actually, "the simplest way of using a for loop an iterating over an array" (the Python type is named "list" BTW) is the second one, ie
实际上,“使用 for 循环迭代数组的最简单方法”(Python 类型被命名为“列表”顺便说一句)是第二个,即
for item in somelist:
do_something_with(item)
which FWIW works for all iterables (lists, tuples, sets, dicts, iterators, generators etc).
FWIW 适用于所有可迭代对象(列表、元组、集合、字典、迭代器、生成器等)。
The range-based C-style version is considered highly unpythonic, and will only work with lists or list-like iterables.
基于范围的 C 风格版本被认为是非常非 Pythonic 的,并且只适用于列表或类似列表的可迭代对象。
What I would like to know is what this does
我想知道的是这是做什么的
for i, j in range(len(array)):
# What is i and j here?
Well, you could just test it by yourself... But the result is obvious: it will raise a TypeError
because unpacking only works on iterables and ints are not iterable.
好吧,您可以自己测试一下……但结果很明显:它会引发 aTypeError
因为解包仅适用于可迭代对象而整数不可迭代。
or
或者
for i, j in array:
# What is i and j in this case?
Depends on what is array
and what it yields when iterating over it. If it's a list of 2-tuples or an iterator yielding 2-tuples, i
and j
will be the elements of the current iteration item, ie:
取决于array
迭代时是什么以及它产生什么。如果它是一个 2-tuples 列表或一个产生 2-tuples 的迭代器,i
并且j
将是当前迭代项的元素,即:
array = [(letter, ord(letter)) for letter in "abcdef"]
for letter, letter_ord in array:
print("{} : {}".format(letter, letter_ord))
Else, it will most probably raise a TypeError too.
否则,它也很可能会引发 TypeError。
Note that if you want to have both the item and index, the solution is the builtin enumerate(sequence)
, which yields an (index, item)
tuple for each item:
请注意,如果您想要同时拥有项目和索引,则解决方案是 builtin enumerate(sequence)
,它(index, item)
为每个项目生成一个元组:
array = list("abcdef")
for index, letter in enumerate(array):
print("{} : {}".format(index, letter)