首页 > 解决方案 > 程序添加两个元素,但它应该只添加一个。Python

问题描述

我正在制作一个简单的数独游戏,但这段代码应该只在列表中添加一个元素,但它添加了两个。虽然它没有造成任何问题,但是当列表变得更大时,我可以减慢程序性能。

这是一段代码:

def typing(text_cor, pos):
    global numbers, equal
    keys = pygame.key.get_pressed()
    if keys[pygame.K_1]:
        numbers = 1
    if keys[pygame.K_8]:
        numbers = 8
    if keys[pygame.K_7]:
        numbers = 7
    if keys[pygame.K_6]:
        numbers = 6
    if keys[pygame.K_5]:
        numbers = 5
    if keys[pygame.K_4]:
        numbers = 4
    if keys[pygame.K_3]:
        numbers = 3
    if keys[pygame.K_2]:
        numbers = 2
    if keys[pygame.K_9]:
        numbers = 9
    if numbers in [1, 2, 3, 4, 5, 6, 7, 8, 9]:
        if len(text_cor) > 0:
            for j in range(len(text_cor) - 1):
                if (
                    pos[0] + 15 == text_cor[j][1] and pos[1] + 10 == text_cor[j][2]
                ) and text_cor[j][0] != 0:
                    equal = True
                    numbers = 0
                if (
                    pos[0] + 15 == text_cor[j][1] and pos[1] + 10 == text_cor[j][2]
                ) and text_cor[j][0] == 0:
                    equal = True
                    text_cor[j][0] = numbers
                    numbers = 0

            if equal == False and numbers != 0:
                text_cor.append([numbers, pos[0] + 15, pos[1] + 10])
                numbers = 0
                equal = True
            else:
                equal = False
                numbers = 0
        if len(text_cor) == 0:
            text_cor.append([numbers, pos[0] + 15, pos[1] + 10])
            numbers = 0

我尝试对其进行编程,使其不会添加相同 x 和 y cor 的任何其他元素。

标签: pythonlistpygame

解决方案


现在它工作正常。代码:

for j in range(-1, len(text_cor)):
            if (
                pos[0] + 15 == text_cor[j][1] and pos[1] + 10 == text_cor[j][2]
            ) and text_cor[j][0] != 0:
                equal = True
                numbers = 0
            if (
                pos[0] + 15 == text_cor[j][1] and pos[1] + 10 == text_cor[j][2]
            ) and text_cor[j][0] == 0:
                equal = True
                text_cor[j][0] = numbers
                numbers = 0
            if (equal == False and j == len(text_cor) - 1) and numbers != 0:
                text_cor.append([numbers, pos[0] + 15, pos[1] + 10])
                equal = False
                numbers = 0
            else:
                equal = False

推荐阅读