如何旋转元组?
How to rotate a tuple?
我有一个带有元组的函数,例如
def rotate_block(block: typing.Tuple[float, float]):
"""
Rotates a block
:param block: a block (width_block, height_block)
"""
return tuple([block[1], block[0]])
如何return方块旋转?我试过这段代码
[(t[1], t[0]) for t in block]
但是不起作用,为什么?
我的输出
Traceback (most recent call last):
File "C:\Users\xxx\Desktop\algorithms\test_unit.py", line 18, in test_rotate_block
self.assertEqual(tg.rotate_block((3,1)), (1,3))
File "C:\Users\xxx\Desktop\algorithms\xx.py", line 31, in rotate_block
[tuple(reversed(t)) for t in block]
File "C:\Users\xxx\Desktop\algorithms\xx.py", line 31, in <listcomp>
[tuple(reversed(t)) for t in block]
TypeError: 'int' object is not reversible
您不需要做任何特别的事情,只需使用元组解包,然后 return 块以相反的顺序:
import typing
def rotate_block(block: typing.Tuple[float, float]):
width, height = block
return height, width
input_block = (3.14, 2.71)
print(rotate_block(input_block))
我有一个带有元组的函数,例如
def rotate_block(block: typing.Tuple[float, float]):
"""
Rotates a block
:param block: a block (width_block, height_block)
"""
return tuple([block[1], block[0]])
如何return方块旋转?我试过这段代码
[(t[1], t[0]) for t in block]
但是不起作用,为什么?
我的输出
Traceback (most recent call last):
File "C:\Users\xxx\Desktop\algorithms\test_unit.py", line 18, in test_rotate_block
self.assertEqual(tg.rotate_block((3,1)), (1,3))
File "C:\Users\xxx\Desktop\algorithms\xx.py", line 31, in rotate_block
[tuple(reversed(t)) for t in block]
File "C:\Users\xxx\Desktop\algorithms\xx.py", line 31, in <listcomp>
[tuple(reversed(t)) for t in block]
TypeError: 'int' object is not reversible
您不需要做任何特别的事情,只需使用元组解包,然后 return 块以相反的顺序:
import typing
def rotate_block(block: typing.Tuple[float, float]):
width, height = block
return height, width
input_block = (3.14, 2.71)
print(rotate_block(input_block))