我目前在一个编码课程中,我正在尝试学习Python(Python3),我在这里为一个作业编写了一些代码,但我显然是把交换搞错了,我不知道如何修复它。我有作业说明,我对我的代码也有评论,我需要帮助理解。有人能告诉我如何通过交换不同的值来翻转行吗
以下是说明:
这是我的代码:
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()
以下是评论:
我该如何做评论中的内容?
嗯,我花了一些时间才意识到这个问题,因为垂直和水平翻转这张图片会得到相同的结果。在您的情况下,您要做的是:
当然,正如Sam Stafford所建议的,你可以让它变得更简单(如果你被允许的话)
您当前的代码实际上运行得很好。您只是忘记了从函数返回翻转的数组:
不需要
flipIt
函数,因为Python有一种内置的方法来实现这一点。您只需更换:与:
(如果您想在其中增加一个抽象层,或者因为赋值要求您有一个专门称为
flipIt
的函数,您也可以执行类似flipIt = lambda img: img.reverse()
的操作。)list.reverse()
方法对任何列表进行操作,并对其元素进行就地反转。由于pic
是图像中的行列表,因此颠倒顺序会产生垂直翻转的效果您还可以通过使用
str.join()
将每一行转换为单个字符串来简化print
循环相关问题 更多 >
编程相关推荐