Python 带有两个变量的“for 循环”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18648626/
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
"for loop" with two variables?
提问by Quester
How can I include two variables in the same for
loop?
如何在同一个for
循环中包含两个变量?
t1 = [a list of integers, strings and lists]
t2 = [another list of integers, strings and lists]
def f(t): #a function that will read lists "t1" and "t2" and return all elements that are identical
for i in range(len(t1)) and for j in range(len(t2)):
...
回答by qaphla
for (i,j) in [(i,j) for i in range(x) for j in range(y)]
should do it.
应该这样做。
回答by Jags
Any reason you can't use a nested for loop?
有什么理由不能使用嵌套的 for 循环?
for i in range(x):
for j in range(y):
#code that uses i and j
回答by SethMMorton
If you want the effect of a nested for loop, use:
如果您想要嵌套 for 循环的效果,请使用:
import itertools
for i, j in itertools.product(range(x), range(y)):
# Stuff...
If you just want to loop simultaneously, use:
如果您只想同时循环,请使用:
for i, j in zip(range(x), range(y)):
# Stuff...
Note that if x
and y
are not the same length, zip
will truncate to the shortest list. As @abarnert pointed out, if you don't want to truncate to the shortest list, you could use itertools.zip_longest
.
请注意,如果x
和y
长度不同,zip
将截断到最短列表。正如@abarnert 指出的那样,如果您不想截断到最短列表,则可以使用itertools.zip_longest
.
UPDATE
更新
Based on the request for "a function that will read lists "t1" and "t2" and return all elements that are identical", I don't think the OP wants zip
orproduct
. I think they want a set
:
基于对“将读取列表“t1”和“t2”并返回所有相同元素的函数的请求,我认为 OP 不想要zip
或product
. 我认为他们想要一个set
:
def equal_elements(t1, t2):
return list(set(t1).intersection(set(t2)))
# You could also do
# return list(set(t1) & set(t2))
The intersection
method of a set
will return all the elements common to it and another set (Note that if your lists contains other list
s, you might want to convert the inner list
s to tuples
first so that they are hashable; otherwise the call to set
will fail.). The list
function then turns the set back into a list.
a 的intersection
方法set
将返回它的所有公共元素和另一个集合(请注意,如果您的列表包含其他list
s,您可能希望将内部list
s转换为tuples
first 以便它们是可散列的;否则调用set
将失败。)。list
然后该函数将集合重新转换为列表。
UPDATE 2
更新 2
OR, the OP might want elements that are identical in the same position in the lists. In this case, zip
would be most appropriate, and the fact that it truncates to the shortest list is what you would want (since it is impossible for there to be the same element at index 9 when one of the lists is only 5 elements long). If that is what you want, go with this:
或者,OP 可能需要在列表中相同位置的元素相同。在这种情况下,zip
将是最合适的,并且它截断到最短列表的事实是您想要的(因为当列表之一只有 5 个元素长时,索引 9 处不可能有相同的元素) . 如果这就是您想要的,请执行以下操作:
def equal_elements(t1, t2):
return [x for x, y in zip(t1, t2) if x == y]
This will return a list containing only the elements that are the same and in the same position in the lists.
这将返回一个列表,该列表仅包含列表中相同且位于相同位置的元素。
回答by Morgan Harris
There's two possible questions here: how can you iterate over those variables simultaneously, or how can you loop over their combination.
这里有两个可能的问题:如何同时迭代这些变量,或者如何循环它们的组合。
Fortunately, there's simple answers to both. First case, you want to use zip
.
幸运的是,两者都有简单的答案。第一种情况,您想使用zip
.
x = [1, 2, 3]
y = [4, 5, 6]
for i, j in zip(x, y):
print(str(i) + " / " + str(j))
will output
会输出
1 / 4
2 / 5
3 / 6
Remember that you can put any iterablein zip
, so you could just as easily write your exmple like:
请记住,您可以将任何可迭代对象放入中zip
,因此您可以轻松地编写如下示例:
for i, j in zip(range(x), range(y)):
# do work here.
Actually, just realised that won't work.It would only iterate until the smaller range ran out. In which case, it sounds like you want to iterate over the combination of loops.
实际上,刚刚意识到这行不通。它只会迭代,直到较小的范围用完。在这种情况下,听起来您想要遍历循环组合。
In the other case, you just want a nested loop.
在另一种情况下,您只需要一个嵌套循环。
for i in x:
for j in y:
print(str(i) + " / " + str(j))
gives you
给你
1 / 4
1 / 5
1 / 6
2 / 4
2 / 5
...
You can also do this as a list comprehension.
您也可以将其作为列表理解来执行。
[str(i) + " / " + str(j) for i in range(x) for j in range(y)]
Hope that helps.
希望有帮助。
回答by kojiro
If you really just have lock-step iteration over a range, you can do it one of several ways:
如果您真的只是在一个范围内进行锁步迭代,您可以通过以下几种方式之一进行:
for i in range(x):
j = i
…
# or
for i, j in enumerate(range(x)):
…
# or
for i, j in ((i,i) for i in range(x)):
…
All of the above are equivalent to for i, j in zip(range(x), range(y))
if x <= y
.
以上所有等价于for i, j in zip(range(x), range(y))
if x <= y
。
If you want a nested loop and you only have two iterables, just use a nested loop:
如果你想要一个嵌套循环并且你只有两个可迭代对象,只需使用嵌套循环:
for i in range(x):
for i in range(y):
…
If you have more than two iterables, use itertools.product
.
如果您有两个以上的可迭代对象,请使用itertools.product
.
Finally, if you want lock-step iteration up to x
and then to continue to y
, you have to decide what the rest of the x
values should be.
最后,如果您希望锁步迭代达到x
,然后继续到y
,您必须决定其余的x
值应该是什么。
for i, j in itertools.zip_longest(range(x), range(y), fillvalue=float('nan')):
…
# or
for i in range(min(x,y)):
j = i
…
for i in range(min(x,y), max(x,y)):
j = float('nan')
…
回答by dawg
I think you are looking for nested loops.
我认为您正在寻找嵌套循环。
Example (based on your edit):
示例(基于您的编辑):
t1=[1,2,'Hello',(1,2),999,1.23]
t2=[1,'Hello',(1,2),999]
t3=[]
for it1, e1 in enumerate(t1):
for it2, e2 in enumerate(t2):
if e1==e2:
t3.append((it1,it2,e1))
# t3=[(0, 0, 1), (2, 1, 'Hello'), (3, 2, (1, 2)), (4, 3, 999)]
Which can be reduced to a single comprehension:
可以简化为一个理解:
[(it1,it2,e1) for it1, e1 in enumerate(t1) for it2, e2 in enumerate(t2) if e1==e2]
But to find the common elements, you can just do:
但是要找到共同元素,您可以这样做:
print set(t1) & set(t2)
# set([(1, 2), 1, 'Hello', 999])
If your list contains non-hashable objects (like other lists, dicts) use a frozen set:
如果您的列表包含不可散列的对象(如其他列表、字典),请使用冻结集:
from collections import Iterable
s1=set(frozenset(e1) if isinstance(e1,Iterable) else e1 for e1 in t1)
s2=set(frozenset(e2) if isinstance(e2,Iterable) else e2 for e2 in t2)
print s1 & s2
回答by Open-Business
"Python 3."
“蟒蛇3。”
Add 2 vars with for loop using zip and range; Returning a list.
使用 zip 和 range 使用 for 循环添加 2 个变量;返回一个列表。
Note: Will only run till smallest range ends.
注意:只会运行到最小范围结束。
>>>a=[g+h for g,h in zip(range(10), range(10))]
>>>a
>>>[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
回答by Daniel
For your use case, it may be easier to utilize a while
loop.
对于您的用例,使用while
循环可能更容易。
t1 = [137, 42]
t2 = ["Hello", "world"]
i = 0
j = 0
while i < len(t1) and j < len(t2):
print t1[i], t2[j]
i += 1
j += 1
# 137 Hello
# 42 world
As a caveat, this approach will truncate to the length of your shortest list.
需要注意的是,这种方法将截断到最短列表的长度。