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

2024-10-02 20:42:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个函数,返回这个:

42334
44423
21142
14221

由此:

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

函数只是遍历列表并从最后一个开始打印它们的元素。我已经能够通过打印得到正确的结果,但我正在尝试使它使函数只返回结果。我该怎么做?我试过发电机,单线循环等,但互联网上的笔记并不多,往往写在一个复杂的方式。。。你知道吗

以下是我目前掌握的代码:

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

Tags: 函数代码元素列表lendef方式互联网
3条回答

您可以更改代码以将项目存储在list中,而不是打印它们。 并将每个list存储在另一个list中,以便返回所有它们。你知道吗

像这样:

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)
>>> 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)变换矩阵。但是,您从最后一列开始,所以我只需添加map(reversed,)来处理这个问题。你知道吗

剩下的只是打印每一行。你知道吗

相关问题 更多 >