简体   繁体   English

用Python编写单行嵌套循环

[英]Writing a single-line nested loop in Python

I'm trying to compress a for loop inside of another for loop into a single line of code. 我正在尝试将另一个for循环内的for循环压缩为一行代码。 This is the full nested loop: 这是完整的嵌套循环:

list_of_numbers = []

for i in range(4):
    for n in range(4):
        list_of_numbers.append(n)

I thought that the below line of code would be the correct way of writing the above code as a single-line nested loop, but it gave the wrong output. 我认为下面的代码行将是将上述代码编写为单行嵌套循环的正确方法,但是它给出了错误的输出。

list_of_numbers = [n for n in range(4) for i in range(4)]

How would this second example of code be modified to do the same as the first? 如何将第二个示例代码修改为与第一个示例相同?

(This question has been reworded, so any answers given before the 13th of August 2019 will be answering the same question using a previous example.) (此问题已被重新措辞,因此在2019年8月13日之前给出的所有答案都将使用前面的示例来回答相同的问题。)

Possibly counter intuitively, in a nested list comprehension you need to follow the same order of the for loops as with the longhand version. 可能直观地进行反击,在嵌套列表理解中,您需要遵循与长手版本相同的for循环顺序。 So: 所以:

[data[((len(data) - 1) - (8 * i)) - (7 - n)] for i in range(int(len(data) / 8)) for n in range(8)]

So the main difference in your solution, is that the order of the generator part is switched. 因此,您的解决方案的主要区别在于生成器部分的顺序已切换。

To transform: 转换:

collection_c = []
for a in collection_a:
   for b in collection_b:
     collection_c.append(a,b)

You would want to do: 您想做:

collection_c = [ (a,b) for a in collection_a for b in collection_b]

So in your example you would end up with 因此,在您的示例中,您最终将获得

new_data = [  data[((len(data) - 1) - (8 * i)) - (7 - n)] for i in range(int(len(data) / 8)) for n in range(8)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM