Python &引用;for loop";有两个变量?

Python &引用;for loop";有两个变量?,python,for-loop,Python,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 f

如何在相同的
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)):
        ...

应该这样做。

有什么原因不能使用嵌套for循环吗

for i in range(x):
   for j in range(y):
       #code that uses i and j

如果要获得嵌套for循环的效果,请使用:

import itertools
for i, j in itertools.product(range(x), range(y)):
    # Stuff...
如果只想同时循环,请使用:

for i, j in zip(range(x), range(y)):
    # Stuff...
请注意,如果
x
y
的长度不相同,
zip
将截断为最短的列表。正如@abarnert所指出的,如果您不想截断到最短的列表,可以使用
itertools.zip\u longest

更新

基于对“一个将读取列表“t1”和“t2”并返回所有相同元素的函数”的请求,我认为OP不需要
zip
product
。我想他们想要一套

def equal_elements(t1, t2):
    return list(set(t1).intersection(set(t2)))
    # You could also do
    # return list(set(t1) & set(t2))
set
intersection
方法将返回它和另一个集合共有的所有元素(请注意,如果您的列表包含其他
list
s,您可能希望首先将内部
list
s转换为
元组,以便它们可以散列;否则对
set
的调用将失败)。然后,
list
功能将集合转换回列表

更新2

或者,OP可能希望元素在列表中的相同位置相同。在这种情况下,
zip
将是最合适的,它将截断为最短的列表这一事实是您想要的(因为当其中一个列表只有5个元素长时,索引9处不可能有相同的元素)。如果这是您想要的,请使用以下选项:

def equal_elements(t1, t2):
    return [x for x, y in zip(t1, t2) if x == y]

这将返回一个列表,其中只包含列表中相同且位置相同的元素。

这里有两个可能的问题:如何同时迭代这些变量,或者如何循环它们的组合

幸运的是,两者都有简单的答案。第一种情况下,您要使用
zip

x = [1, 2, 3]
y = [4, 5, 6]

for i, j in zip(x, y):
   print(str(i) + " / " + str(j))
将输出

1 / 4
2 / 5
3 / 6
请记住,您可以将任何iterable放入
zip
,这样您就可以轻松编写示例,如:

for i, j in zip(range(x), range(y)):
    # do work here.
实际上,刚刚意识到这是行不通的。它只会迭代,直到较小的范围用完为止。在这种情况下,听起来您希望迭代循环的组合

在另一种情况下,您只需要一个嵌套循环

for i in x:
    for j in y:
        print(str(i) + " / " + str(j))
给你

1 / 4
1 / 5
1 / 6
2 / 4
2 / 5
...
您也可以将其作为列表进行理解

[str(i) + " / " + str(j) for i in range(x) for j in range(y)]

希望这能有所帮助。

如果您真的只是在一个范围内进行锁步迭代,您可以使用以下几种方法之一:

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)):
  …

以上所有这些都相当于zip中i,j的
(范围(x),范围(y))
如果
x我想您正在寻找嵌套循环

示例(基于您的编辑):

可以简化为一种理解:

[(it1,it2,e1) for it1, e1 in enumerate(t1) for it2, e2 in enumerate(t2) if e1==e2] 
但要找到常见元素,您只需执行以下操作:

print set(t1) & set(t2)
# set([(1, 2), 1, 'Hello', 999])
如果列表包含不可散列的对象(如其他列表、DICT),请使用冻结集:

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
“Python 3。”

添加2个变量,使用zip和range进行for循环;返回列表

注意:将只运行到最小范围结束

>>>a=[g+h for g,h in zip(range(10), range(10))]
>>>a
>>>[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

对于您的用例,使用循环可能更容易

t1=[137,42]
t2=[“你好”,“世界”]
i=0
j=0
而i

作为警告,此方法将截短到最短列表的长度。

x和y是两个列表吗?@user2246674
zip
在iterables具有相同长度时很好。是否希望类似于一行中的嵌套循环,或者只是同时迭代列表?以防SethMMorton的问题不清楚:如果
x
y
都是3,同时(也称为“锁步”或“并行”)迭代会给你
0,0
,然后
1,1
然后
2,2
;嵌套迭代将为您提供
0,0
0,1
0,2
1,0
1,1
1,2
2,0
2,1
2,2
。(或者你甚至想要与两者不同的东西?在这种情况下,请解释一下。)我没有投反对票,但可能是因为不清楚你想要的是同时循环还是嵌套循环,甚至在评论者要求澄清之后。这只是Matt Quinlan答案中嵌套for循环的一个更难理解的变体。看起来像《盗梦空间》:)-1
zip
答案不合格。正如我在上面所评论的,它只有在
x==y
的情况下才有效。@kojiro:嗯,OP没有指定如果
x!=y
。一旦他解释了,答案要么是
zip
,要么是
itertools.zip\u longest
。没有zip有同时迭代吗?@Quester:当然。文档甚至向您展示了如何编写这些函数的精确等价物。但通常这是最简单的方法。@Quester您可以使用
itertools.izip
,这基本上是一样的。除此之外,我不知道。但是
zip
有什么问题吗?@Matt:我觉得它不够优雅。@Quester:你可以用
product
来代替,就像SethMMorton的回答一样。如果您有6个范围而不是2个,或者它们的数量是动态的,并且只有在运行时才知道,那么这肯定会更优雅/可读。但对于其中的两个来说……为了简单起见,很难打败两个嵌套循环。谁不喜欢通过缩进来让python开心呢?嵌套循环运行了i*j次。如果他只想运行i次,考虑到i==j@abarnert“>为了简单起见,很难击败2个嵌套循环。”我在一个项目中工作,该项目要求我为范围内的I(len(…):为rnage中的j(len(…)
)键入数百次“
”…如果我知道这一点,我就可以节省很多时间“
对于网格中的(i,j):
”链接到Python文档!如果
[(it1,it2,e1) for it1, e1 in enumerate(t1) for it2, e2 in enumerate(t2) if e1==e2] 
print set(t1) & set(t2)
# set([(1, 2), 1, 'Hello', 999])
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
>>>a=[g+h for g,h in zip(range(10), range(10))]
>>>a
>>>[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
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