如何使用 python 中的切片运算符水平翻转列表的行?

How to flip the rows of a list horizontally using slicing operator in python?

def matrixflip(myl,c):
   if(c=='v'):
       myl=myl[::-1]
       return myl
   elif(c=='h'):
       myl=myl[::][::-1]
       return myl
   else:
       return myl

myl=[[1, 2], [3, 4]]
print(matrixflip(myl,'h'))

预期输出:[[2,1],[4,3]]

在上面的代码中,我调用了 matrixflip() 函数来翻转列表的行/通过将第二个参数作为 'h' 传递来水平翻转二维矩阵。但是,我仍然得到垂直翻转的版本。

您需要反转每个子列表。最简单的方法可能是使用列表理解表达式:

result = [x[::-1] for x in myl]