简体   繁体   English

在python中的while循环中返回循环

[英]Returning for loop inside a while loop in python

I'm trying to make a function that returns this: 我正在尝试创建一个返回此函数的函数:

42334
44423
21142
14221

From this: 由此:

polje = [[1, 2, 4, 4], [4, 1, 4, 2], [2, 1, 4, 3], [2, 4, 2, 3], [1, 2, 3, 4]]

The function just goes through the lists and prints their elements starting with the last ones. 该函数只是遍历列表并从最后一个开始打印它们的元素。 I've been able to get the right result by printing, but i'm trying to make it so that the function simply returns the result. 我已经能够通过打印获得正确的结果,但我正在尝试使其能够简单地返回结果。 How do i do it? 我该怎么做? I've tried generators, single line for loops etc. but notes on the internet are not plentiful and are often writen in a complicated way... 我已经尝试过发电机,单线换环等等但是互联网上的笔记并不丰富,而且经常以复杂的方式写出......

Here's the code i've got so far: 这是我到目前为止的代码:

def izpisi(polje):
    i = len(polje[0]) - 1
    while i >= 0:
        for e in polje:
            print(e[i], end="")
        i -= 1
        print("\n")
    return 0
>>> polje = [[1, 2, 4, 4], [4, 1, 4, 2], [2, 1, 4, 3], [2, 4, 2, 3], [1, 2, 3, 4]]
>>> def izpisi(polje):
        return zip(*map(reversed, polje))

>>> for line in izpisi(polje):
        print(*line, sep='')


42334
44423
21142
14221

zip(*x) transposes a matrix. zip(*x)转置矩阵。 However you start at the last column so I simply add map(reversed,) to handle that. 但是你从最后一列开始,所以我只需添加map(reversed,)来处理它。

The rest is just printing each line. 剩下的就是打印每一行。

you can change your code to store the items in a list instead of print them. 您可以更改代码以将项目存储在list而不是打印它们。 and store each list in another list in order to return all of them. 并将每个list存储在另一个list中以便返回所有list

like this: 像这样:

def izpisi(polje):
    a = []
    i = len(polje[0]) - 1
    while i >= 0:
        l = []
        for e in polje:
            l.append(e[i])
        i -= 1
        a.append(l)
    return a
def izpisi(polje):
    return '\n'.join([ # inserts '\n' between the lines
        ''.join(map(str, sublst)) # converts list to string of numbers
        for sublst in zip(*polje) # zip(*...) transposes your matrix
    ][::-1]) # [::-1] reverses the list

polje = [[1, 2, 4, 4], [4, 1, 4, 2], [2, 1, 4, 3], [2, 4, 2, 3], [1, 2, 3, 4]]
print izpisi(polje)

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

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