如何交换元组中的元素?

时间:2011-12-05 21:59:15

标签: 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)]

我如何交换?

1 个答案:

答案 0 :(得分:6)

Tuples, like strings, are immutable: it is not possible to assign to the individual items of a tuple

Lists是可变的,因此将您的board_state转换为list list

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

然后使用标准Python惯用语swapping two elements in a list

>>> 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]]
相关问题