“for循环"有两个变量? [英] "for loop" with two variables?

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

问题描述

如何在同一个 for 循环中包含两个变量?

How can I include two variables in the same for loop?

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 循环的效果,请使用:

If you want the effect of a nested for loop, use:

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...

注意,如果xy 的长度不同,zip 将截断到最短的列表.正如@abarnert 指出的,如果你不想截断到最短的列表,你可以使用 itertools.zip_longest.

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.

更新

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

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 or product. I think they want a set:

def equal_elements(t1, t2):
    return list(set(t1).intersection(set(t2)))
    # You could also do
    # return list(set(t1) & set(t2))

setintersection 方法将返回它和另一个集合共有的所有元素(请注意,如果您的列表包含其他 lists,您可能希望首先将内部 lists 转换为 tuples 以便它们是可散列的;否则对 set 的调用将失败.).list 函数然后将集合重新转换为列表.

The intersection method of a set will return all the elements common to it and another set (Note that if your lists contains other lists, you might want to convert the inner lists 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.

更新 2

OR,OP 可能想要列表中相同位置的元素.在这种情况下, zip 将是最合适的,并且它截断到最短列表这一事实正是您想要的(因为在以下情况之一时,索引 9 处不可能有相同的元素)列表只有 5 个元素长).如果这就是您想要的,请执行以下操作:

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:

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.

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

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