python – 如何交换元组中的元素?

我有一个非常具体的问题,我需要知道如何交换列表或元组中的元素.
我有一个名为board state的列表,我知道需要交换的元素.我该如何交换它们?在具有二维数组的 java中,我可以轻松地执行标准交换技术,但是在这里它说元组赋值是不可能的.

这是我的代码:

board_state = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]

new = [1, 1] # [row, column] The '4' element here needs to be swapped with original
original = [2, 1] # [row, column] The '7' element here needs to be swapped with new

结果应该是:

board_state = [(0, 1, 2), (3, 7, 5), (6, 4, 8)]

我如何交换?

最佳答案
Tuples, like strings, are immutable: it is not possible to assign to the individual items of a tuple.

Lists是可变的,因此将board_state转换为列表列表:

>>> board_state = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]

然后使用swapping two elements in a list的标准Python习语:

>>> board_state[1][1], board_state[2][1] = board_state[2][1], board_state[1][1]
>>> board_state
[[0, 1, 2], [3, 7, 5], [6, 4, 8]]
点击查看更多相关文章

转载注明原文:python – 如何交换元组中的元素? - 乐贴网