Python 单行嵌套 For 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17006641/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:12:31  来源:igfitidea点击:

Single Line Nested For Loops

pythonloopsfor-loopnestednested-loops

提问by Asher Garland

Wrote this function in python that transposes a matrix:

用python编写了这个转置矩阵的函数:

def transpose(m):
    height = len(m)
    width = len(m[0])
    return [ [ m[i][j] for i in range(0, height) ] for j in range(0, width) ]

In the process I realized I don't fully understand how single line nested for loops execute. Please help me understand by answering the following questions:

在这个过程中,我意识到我并不完全理解单行嵌套的 for 循环是如何执行的。请回答以下问题帮助我理解:

  1. What is the order in which this for loop executes?
  2. If I had a triple nested for loop, what order would it execute?
  3. What would be equal the equal unnested for loop?
  1. 这个 for 循环的执行顺序是什么?
  2. 如果我有一个三重嵌套的 for 循环,它会按什么顺序执行?
  3. 什么是相等的非嵌套 for 循环?

Given,

鉴于,

[ function(i,j) for i,j in object ]
  1. What type must object be in order to use this for loop structure?
  2. What is the order in which i and j are assigned to elements in object?
  3. Can it be simulated by a different for loop structure?
  4. Can this for loop be nested with a similar or different structure for loop? And how would it look?
  1. 为了使用这个 for 循环结构,对象必须是什么类型?
  2. 将 i 和 j 分配给对象中的元素的顺序是什么?
  3. 可以用不同的for循环结构来模拟吗?
  4. 这个 for 循环可以嵌套一个相似或不同的 for 循环结构吗?它会是什么样子?

Additional information is appreciated as well.

额外的信息也值得赞赏。

采纳答案by Jeff Tratner

The best source of information is the official Python tutorial on list comprehensions. List comprehensions are nearly the same as for loops (certainly any list comprehension can be written as a for-loop) but they are often faster than using a for loop.

最好的信息来源是关于列表推导式官方 Python 教程。列表推导与 for 循环几乎相同(当然,任何列表推导都可以写为 for 循环),但它们通常比使用 for 循环更快。

Look at this longer list comprehension from the tutorial (the ifpart filters the comprehension, only parts that pass the if statement are passed into the final part of the list comprehension (here (x,y)):

从教程中查看这个较长的列表推导式(该if部分过滤推导式,只有通过 if 语句的部分才会被传递到列表推导式的最后部分(此处(x,y)):

>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

It's exactly the same as this nested for loop (and, as the tutorial says, note how the order of for and if are the same).

它与这个嵌套的 for 循环完全相同(并且,正如教程所说,注意 for 和 if 的顺序是如何相同的)。

>>> combs = []
>>> for x in [1,2,3]:
...     for y in [3,1,4]:
...         if x != y:
...             combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

The major differencebetween a list comprehension and a for loop is that the final part of the for loop (where you do something) comes at the beginning rather than at the end.

列表推导式和 for 循环之间的主要区别在于 for 循环的最后部分(你做某事的地方)出现在开头而不是结尾。

On to your questions:

关于你的问题:

What type must object be in order to use this for loop structure?

为了使用这个 for 循环结构,对象必须是什么类型?

An iterable. Any object that can generate a (finite) set of elements. These include any container, lists, sets, generators, etc.

一个可迭代的. 任何可以生成(有限)元素集的对象。这些包括任何容器、列表、集合、生成器等。

What is the order in which i and j are assigned to elements in object?

将 i 和 j 分配给对象中的元素的顺序是什么?

They are assigned in exactly the same order as they are generated from each list, as if they were in a nested for loop (for your first comprehension you'd get 1 element for i, then every value from j, 2nd element into i, then every value from j, etc.)

它们的分配顺序与从每个列表中生成的顺序完全相同,就好像它们在嵌套的 for 循环中一样(对于您的第一次理解,您将获得 i 的 1 个元素,然后是 j 的每个值,第二个元素到 i,然后来自 j 的每个值,等等)

Can it be simulated by a different for loop structure?

可以用不同的for循环结构来模拟吗?

Yes, already shown above.

是的,上面已经显示了。

Can this for loop be nested with a similar or different structure for loop? And how would it look?

这个 for 循环可以嵌套一个相似或不同的 for 循环结构吗?它会是什么样子?

Sure, but it's not a great idea. Here, for example, gives you a list of lists of characters:

当然,但这不是一个好主意。例如,这里为您提供了一个字符列表列表:

[[ch for ch in word] for word in ("apple", "banana", "pear", "the", "hello")]

回答by korylprince

First of all, your first code doesn't use a for loop per se, but a list comprehension.

首先,您的第一个代码本身不使用 for 循环,而是使用列表理解

  1. Would be equivalent to

    for j in range(0, width): for i in range(0, height): m[i][j]

  2. Much the same way, it generally nests like for loops, right to left. But list comprehension syntax is more complex.

  3. I'm not sure what this question is asking

  1. 将相当于

    for j in range(0, width): for i in range(0, height): m[i][j]

  2. 以同样的方式,它通常像 for 循环一样嵌套,从右到左。但是列表理解语法更复杂。

  3. 我不确定这个问题在问什么



  1. Any iterable object that yields iterable objects that yield exactly two objects (what a mouthful - i.e [(1,2),'ab']would be valid )

  2. The order in which the object yields upon iteration. igoes to the first yield, jthe second.

  3. Yes, but not as pretty. I believe it is functionally equivalent to:

    l = list()
    for i,j in object:
        l.append(function(i,j))
    

    or even better use map:

    map(function, object)
    

    But of course function would have to get i, jitself.

  4. Isn't this the same question as 3?

  1. 任何产生恰好产生两个对象的可迭代对象的可迭代对象(多口——即[(1,2),'ab']有效)

  2. 对象在迭代时产生的顺序。i转到第一个收益,j第二个。

  3. 是的,但没有那么漂亮。我相信它在功能上等同于:

    l = list()
    for i,j in object:
        l.append(function(i,j))
    

    甚至更好地使用map

    map(function, object)
    

    但当然函数必须得到i,j本身。

  4. 这不是和3一样的问题吗?

回答by Lynn

You might be interested in itertools.product, which returns an iterable yielding tuples of values from all the iterables you pass it. That is, itertools.product(A, B)yields all values of the form (a, b), where the avalues come from Aand the bvalues come from B. For example:

您可能对 感兴趣itertools.product,它从您传递给它的所有可迭代对象中返回一个可迭代对象,产生值的元组。也就是说,itertools.product(A, B)产生形式为 的所有值(a, b),其中a值来自A并且b值来自B。例如:

import itertools

A = [50, 60, 70]
B = [0.1, 0.2, 0.3, 0.4]

print [a + b for a, b in itertools.product(A, B)]

This prints:

这打印:

[50.1, 50.2, 50.3, 50.4, 60.1, 60.2, 60.3, 60.4, 70.1, 70.2, 70.3, 70.4]

Notice how the final argument passed to itertools.productis the "inner" one. Generally, itertools.product(a0, a1, ... an)is equal to [(i0, i1, ... in) for inin anfor in-1in an-1... for i0in a0]

注意传递给的最后一个参数itertools.product是“内部”参数。一般来说,等于itertools.product(a0, a1, ... an)[(i0, i1, ... in) for inin anfor in-1in an-1... for i0in a0]

回答by rameshbabu reddy

Below code for best examples for nested loops, while using two for loops please remember the output of the first loop is input for the second loop. Loop termination also important while using the nested loops

下面是嵌套循环最佳示例的代码,在使用两个 for 循环时,请记住第一个循环的输出是第二个循环的输入。使用嵌套循环时循环终止也很重要

for x in range(1, 10, 1):
     for y in range(1,x):
             print y,
        print
OutPut :
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8

回答by Muhammad Abbas

You can use two for loops in same line by using zipfunction

您可以使用zip函数在同一行中使用两个 for 循环

Code:

代码:

list1 = ['Abbas', 'Ali', 'Usman']
list2 = ['Kamran', 'Asgar', 'Hamza', 'Umer']
list3 = []
for i,j in zip(list1,list2):
    list3.append(i)
    list3.append(j)
print(list3)

Output:

输出:

['Abbas', 'Kamran', 'Ali', 'Asgar', 'Usman', 'Hamza']

['Abbas', 'Kamran', 'Ali', 'Asgar', 'Usman', 'Hamza']

So, by using zip function, we can use two for loops or we can iterate two lists in same row.

因此,通过使用 zip 函数,我们可以使用两个 for 循环,或者我们可以在同一行中迭代两个列表。