如何交换函数中的行和不同的值?

2024-10-02 04:30:05 发布

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

我目前在一个编码课程中,我正在尝试学习Python(Python3),我在这里为一个作业编写了一些代码,但我显然是把交换搞错了,我不知道如何修复它。我有作业说明,我对我的代码也有评论,我需要帮助理解。有人能告诉我如何通过交换不同的值来翻转行吗

以下是说明:

enter image description here

这是我的代码:

def flipIt(array):
    for i in range(len(array)):
        length = len(array[i])
        for j in range(length // 2):
            temp = array[i][j]
            array[i][j] = array[i][length - 1 - j]
            array[i][length - 1 - j] = temp


pic = [['@', ' ', ' ', ' ', ' ', '@'],
       ['@', '@', ' ', ' ', ' ', '@'],
       ['@', ' ', '@', ' ', ' ', '@'],
       ['@', ' ', ' ', '@', ' ', '@'],
       ['@', ' ', ' ', ' ', '@', '@'],
       ['@', ' ', ' ', ' ', ' ', '@']]


flipIt(pic)
for i in pic:
    for j in i:
        print(j,end=' ')
    print()

以下是评论:

enter image description here

我该如何做评论中的内容?


Tags: 代码in编码forlen作业评论range
3条回答

嗯,我花了一些时间才意识到这个问题,因为垂直和水平翻转这张图片会得到相同的结果。在您的情况下,您要做的是:

def flipIt(array):
    height = len(array)
    for i in range(len(array) // 2):
        temp = array[i]
        array[i] = array[height-1-i]
        array[height-1-i] = temp
    # No need for return because it is modified in place

pic = [['@', ' ', ' ', ' ', ' ', '@'],
       ['@', '@', ' ', ' ', ' ', '@'],
       ['@', ' ', '@', ' ', ' ', '@'],
       ['@', ' ', ' ', '@', ' ', '@'],
       ['@', ' ', ' ', ' ', '@', '@'],
       ['@', ' ', ' ', ' ', ' ', '@']]


flipIt(pic)
for i in pic:
    for j in i:
        print(j,end=' ')
    print()

当然,正如Sam Stafford所建议的,你可以让它变得更简单(如果你被允许的话)

def flipIt(array):
    array.reverse()

您当前的代码实际上运行得很好。您只是忘记了从函数返回翻转的数组:

def flipit(array):
    for i in range(len(array)):
        length = len(array[i])
        for j in range(length // 2):
            temp = array[i][j]
            array[i][j] = array[i][length - 1 - j]
            array[i][length -1 -j] = temp
    return array

pic = [['@', ' ', ' ', ' ', ' ', '@'],
    ['@', '@', ' ', ' ', ' ', '@'],
    ['@', ' ', '@', ' ', ' ', '@'],
    ['@', ' ', ' ', '@', ' ', '@'],
    ['@', ' ', ' ', ' ', '@', '@'],
    ['@', ' ', ' ', ' ', ' ', '@']
   ]

x = flipit(pic)

print(x)

不需要flipIt函数,因为Python有一种内置的方法来实现这一点。您只需更换:

flipIt(pic)

与:

pic.reverse()

(如果您想在其中增加一个抽象层,或者因为赋值要求您有一个专门称为flipIt的函数,您也可以执行类似flipIt = lambda img: img.reverse()的操作。)

list.reverse()方法对任何列表进行操作,并对其元素进行就地反转。由于pic是图像中的行列表,因此颠倒顺序会产生垂直翻转的效果

您还可以通过使用str.join()将每一行转换为单个字符串来简化print循环

>>> pic = [['@', ' ', ' ', ' ', ' ', '@'],
...        ['@', '@', ' ', ' ', ' ', '@'],
...        ['@', ' ', '@', ' ', ' ', '@'],
...        ['@', ' ', ' ', '@', ' ', '@'],
...        ['@', ' ', ' ', ' ', '@', '@'],
...        ['@', ' ', ' ', ' ', ' ', '@']]
>>> pic.reverse()  # flip the rows from top to bottom
>>> for row in pic:
...     print(' '.join(row))
...
@         @
@       @ @
@     @   @
@   @     @
@ @       @
@         @

相关问题 更多 >

    热门问题