P
P
pyblpovishaisa2021-01-27 21:14:24
Python
pyblpovishaisa, 2021-01-27 21:14:24

How to swap column and row in nested python list?

Trying to write my own 2048 version but ran into a problem. I'm trying to write the movement of numbers up, for this I need to sort the list horizontally so that twos are on the left, and then zeros go and swap columns and rows to make it work. I tried many solutions to the problem, but I can not solve it.

import pygame
import sys
import random

pygame.init()
SIZE_BLOCK = 100
MARGIN = 5
WIDTH = HEIGHT = SIZE_BLOCK * 4 + MARGIN * 5

BLACK = 0, 0, 0
RED = 255, 0, 0
GREEN = 0, 255, 0
WHITE = 255, 255, 255


def pretty_print(list):
    for j in list:
        print(j)
    print('-' * 25)


def left_sort_in_mas(list):
    # Подсчитываем количесво нулей в словаре
    zeroes_count = list.count(0)
    # Создаем словарь с количеством нулей zeroes_count
    zeroes_count_list = [0] * zeroes_count
    len_row = len(list)
    while zeroes_count_list != list[len_row - zeroes_count:]:
        first_zero_index = list.index(0)
        del list[first_zero_index]
        list.append(0)
    return list


# Функция возвращает индекс последнего элемента со значением number в списке row
def found_last_number(row, number):
    try:
        zero_index = row.index(number)
        number_count = row.count(number)
        iteration_count = 1
        while number_count != iteration_count:
            zero_index = row.index(number, zero_index + 1, len(row) - 1)
            iteration_count += 1
        return zero_index
    except ValueError:
        zero_index = -1
        return zero_index


screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('2048')

mas = [[0] * 4 for i in range(4)]


# Стараюсь создать в массиве множество двое, чтобы проверить логику игры. Решение, конечно, временное =)
def random_2():
    mas[random.randint(0, 3)][random.randint(0, 3)] = 2
    mas[random.randint(0, 3)][random.randint(0, 3)] = 2
    mas[random.randint(0, 3)][random.randint(0, 3)] = 2


random_2()
random_2()
random_2()
random_2()


while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                for row in mas:
                    left_sort_in_mas(row)

            if event.key == pygame.K_RIGHT:
                for row in mas:
                    # Подсчет количества нулей
                    zeroes_count = row.count(0)
                    # Создаем список из количества нулей в row
                    zeroes_count_list = [0] * zeroes_count
                    # Пока эти списки не будут равный переносим нули влево
                    while zeroes_count_list != row[:zeroes_count]:
                        last_zero_index = found_last_number(row, 0)
                        if last_zero_index >= 0 or last_zero_index <= 3:
                            del row[last_zero_index]
                            row.insert(0, 0)
                            print(row)
                        else:
                            continue

            elif event.key == pygame.K_UP:
                mas_row_sorted = []
                print(mas)
                # Создаём новый список идентичный mas, но отсортированный
                for j in mas:
                    mas_row_sorted.append(left_sort_in_mas(j))

                print(mas_row_sorted)
                mas = [[0] * 4 for i in range(4)]

                # Не получается заменить столбец на колонку!!!
                # Деление на 2, поскольку заменяю сверху и снизу сразу
                for row in range(len(mas_row_sorted) // 2):
                    for column in range(len(mas_row_sorted)):
                        mas[row][column] = mas_row_sorted[column][row]
                        mas[column][row] = mas_row_sorted[row][column]

    for row in range(4):
        for col in range(4):
            x = col * SIZE_BLOCK + (col + 1) * MARGIN
            y = row * SIZE_BLOCK + (row + 1) * MARGIN
            pygame.draw.rect(screen, WHITE, (x, y, SIZE_BLOCK, SIZE_BLOCK))
            font = pygame.font.SysFont('stxingkai', 80)
            text_1 = font.render(str(mas[row][col]), True, BLACK)
            screen.blit(text_1, (x,  y))

    pygame.display.flip()

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
A
Alan Gibizov, 2021-01-27
@pyblpovishaisa

In short, if you need to transpose, then:

transposed_massive = list(map(list, zip(*massive)))

and if you turn
rotated_massive = list(map(list, zip(*massive[::-1])))

just for the sake of Control, Alt and holy Del, don't redefine list...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question