IT

튜플을 목록으로 변환

lottoking 2020. 5. 29. 08:19
반응형

튜플을 목록으로 변환


저는 현재 타일 맵을 사용하여 파이 게임 게임 용 맵 편집기에서 작업하고 있습니다. 레벨은 다음 구조의 블록으로 구성됩니다 (훨씬 더 큼).

level1 = (
         (1,1,1,1,1,1)
         (1,0,0,0,0,1)
         (1,0,0,0,0,1)
         (1,0,0,0,0,1)
         (1,0,0,0,0,1)
         (1,1,1,1,1,1))

여기서 "1"은 벽인 블록이고 "0"은 빈 공기 인 블록입니다.

다음 코드는 기본적으로 블록 유형 변경을 처리하는 코드입니다.

clicked = pygame.mouse.get_pressed()
if clicked[0] == 1:
    currLevel[((mousey+cameraY)/60)][((mousex+cameraX)/60)] = 1

그러나 레벨이 튜플에 저장되어 있으므로 다른 블록의 값을 변경할 수 없습니다. 레벨에서 다른 값을 쉽게 변경하는 방법은 무엇입니까?


튜플을리스트로 변환 :

>>> t = ('my', 'name', 'is', 'mr', 'tuple')
>>> t
('my', 'name', 'is', 'mr', 'tuple')
>>> list(t)
['my', 'name', 'is', 'mr', 'tuple']

리스트를 튜플로 변환 :

>>> l = ['my', 'name', 'is', 'mr', 'list']
>>> l
['my', 'name', 'is', 'mr', 'list']
>>> tuple(l)
('my', 'name', 'is', 'mr', 'list')

튜플 튜플이 있습니다.
모든 튜플을 목록으로 변환하려면 :

[list(i) for i in level] # list of lists

--- 또는 ---

map(list, level)

편집이 끝나면 다시 변환하십시오.

tuple(tuple(i) for i in edited) # tuple of tuples

--- 또는 --- (감사합니다 @jamylak)

tuple(itertools.imap(tuple, edited))

numpy 배열을 사용할 수도 있습니다.

>>> a = numpy.array(level1)
>>> a
array([[1, 1, 1, 1, 1, 1],
       [1, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 1],
       [1, 1, 1, 1, 1, 1]])

조작 :

if clicked[0] == 1:
    x = (mousey + cameraY) // 60 # For readability
    y = (mousex + cameraX) // 60 # For readability
    a[x][y] = 1

리스트리스트를 가질 수 있습니다. 다음을 사용하여 튜플 튜플을 목록 목록으로 변환하십시오.

level1 = [list(row) for row in level1]

또는

level1 = map(list, level1)

적절하게 수정하십시오.

그러나 numpy 배열 은 더 시원합니다.


튜플을 목록으로 변환하려면

(주어진 질문에서 튜플 사이에 쉼표가 누락되어 오류 메시지를 방지하기 위해 추가되었습니다)

방법 1 :

level1 = (
     (1,1,1,1,1,1),
     (1,0,0,0,0,1),
     (1,0,0,0,0,1),
     (1,0,0,0,0,1),
     (1,0,0,0,0,1),
     (1,1,1,1,1,1))

level1 = [list(row) for row in level1]

print(level1)

방법 2 :

level1 = map(list,level1)

print(list(level1))

방법 1 소요 --- 0.0019991397857666016 초 ---

방법 2는 --- 0.0010001659393310547 초 ---


유형을 튜플에서 목록으로 또는 그 반대로 변환하지 마십시오.

level1 = (
     (1,1,1,1,1,1)
     (1,0,0,0,0,1)
     (1,0,0,0,0,1)
     (1,0,0,0,0,1)
     (1,0,0,0,0,1)
     (1,1,1,1,1,1))

print(level1)

level1 = list(level1)

print(level1)

level1 = tuple(level1)

print(level1)

두 가지 답변 모두 훌륭하지만 약간의 조언이 있습니다.

튜플은 변경할 수 없으므로 변경할 수 없습니다. 따라서 데이터를 조작해야하는 경우 목록에 데이터를 저장하는 것이 좋으며 불필요한 오버 헤드가 줄어 듭니다.

In your case extract the data to a list, as shown by eumiro, and after modifying create a similar tuple of similar structure as answer given by Schoolboy.

Also as suggested using numpy array is a better option


You could dramatically speed up your stuff if you used just one list instead of a list of lists. This is possible of course only if all your inner lists are of the same size (which is true in your example, so I just assume this).

WIDTH = 6
level1 = [ 1,1,1,1,1,1,
           1,0,0,0,0,1,
           1,0,0,0,0,1,
           1,0,0,0,0,1,
           1,0,0,0,0,1,
           1,1,1,1,1,1 ]
print level1[x + y*WIDTH]  # print value at (x,y)

And you could be even faster if you used a bitfield instead of a list:

WIDTH = 8  # better align your width to bytes, eases things later
level1 = 0xFC84848484FC  # bit field representation of the level
print "1" if level1 & mask(x, y) else "0"  # print bit at (x, y)
level1 |= mask(x, y)  # set bit at (x, y)
level1 &= ~mask(x, y)  # clear bit at (x, y)

with

def mask(x, y):
  return 1 << (WIDTH-x + y*WIDTH)

But that's working only if your fields just contain 0 or 1 of course. If you need more values, you'd have to combine several bits which would make the issue much more complicated.


List to Tuple and back can be done as below

import ast, sys
input_str = sys.stdin.read()
input_tuple = ast.literal_eval(input_str)

l = list(input_tuple)
l.append('Python')
#print(l)
tuple_2 = tuple(l)

# Make sure to name the final tuple 'tuple_2'
print(tuple_2)

참고URL : https://stackoverflow.com/questions/16296643/convert-tuple-to-list-and-back

반응형