2011-12-05 3 views
3

필자는 목록이나 튜플에서 요소를 교환하는 방법을 알아야하는 매우 특정한 문제가 있습니다. 보드 상태라고하는 목록이 하나 있는데 스왑해야하는 요소를 알고 있습니다. 어떻게 교환합니까? 2 차원 배열이있는 자바에서 표준 스왑 기법을 쉽게 수행 할 수 있지만 튜플 할당은 불가능합니다.튜플에서 요소를 바꾸는 방법은 무엇입니까?

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)] 

여기

내 코드?

답변

6

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

Lists은 변경할 수 있습니다, 그래서 당신의 board_statelistlist의의 변환 :

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

그리고 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]] 
관련 문제