Python : 내부 목록에서 목록을 제거하면 다음 결과가 발생합니다. IndexError : list index out of range

derek.baxter

저는 파이썬 초보자 일 뿐이므로 참아주세요. 다른 목록에서 목록 중 하나를 제거 할 때 문제가있는 것 같습니다. 목록 안에 목록이 하나만 있으면 코드가 완벽하게 작동하지만 목록 안에 두 개의 목록이 있으면 그 중 하나를 삭제할 때 프로그램이 충돌합니다.

import pygame
import math

pygame.init()

BLACK    = (   0,   0,   0)
WHITE    = ( 255, 255, 255)
GREEN    = (   0, 255,   0)
RED      = ( 255,   0,   0)
BLUE     = (   0,   0, 255)

PI = math.pi

size = (700, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Arcade game!")

background_image = pygame.image.load("bg_one.jpg").convert()
player_image = pygame.image.load("player.png").convert()
player_image.set_colorkey(BLACK)

click_sound = pygame.mixer.Sound("laser5.ogg")

done = False

clock = pygame.time.Clock()

bullets = []

def create_bullet(mpos): 
    bullets.insert(len(bullets), [mpos[0]+50, mpos[1]]) 

while not done: 
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        elif event.type == pygame.MOUSEBUTTONDOWN:
            click_sound.play()
            create_bullet(pygame.mouse.get_pos())

    screen.fill(BLACK)
    # Hide mouse, etc.
    pygame.mouse.set_visible(False)
    # Game Logic
    player_position = pygame.mouse.get_pos()
    x = player_position[0]
    y = player_position[1]
    if not len(bullets) <= 0:
        for i in range(len(bullets)):
            if bullets[i][1] < 0:
                print (bullets)
                bullets.remove(bullets[i])
                print (bullets)
            else:
                bullets[i][1] -= 5      
    # Drawing code goes here
    screen.blit (background_image, [0, 0])
    for i in range(len(bullets)):
        pygame.draw.ellipse(screen, GREEN, [bullets[i][0], bullets[i][1], 4, 4])
    screen.blit (player_image, [x, y])

    pygame.display.flip()

    clock.tick(60)

print(bullets)
pygame.quit()

편집 : 오류를 포함하는 것을 잊었습니다. 여기있어

Traceback (most recent call last):
  File "main.py", line 52, in <module>
    bullets.remove(bullets.index(i))
ValueError: 0 is not in list
캐롤라인 허먼스

당신의 문제를 봅니다. 여기,

for i in range(len(bullets)):
        if bullets[i][1] < 0:
            print (bullets)
            bullets.remove(bullets[i])
            print (bullets)

배열 [ "a", "b"]가 있다고 가정 해 보겠습니다. 이 배열을 순환하고 두 요소를 모두 제거하고 싶습니다. "a"는 인덱스 0에 있고 "b"는 인덱스 1에 있습니다. 이제 배열에서 "a"를 제거합니다.

array.remove(array[0])

이제 내 배열에는 [ "b"] 만 포함됩니다. 그러나 이제 "b"는 인덱스 0에 있습니다. 그러나 이제 더 이상 존재하지 않는 배열의 요소 1에 액세스하려고합니다.

문제는 배열의 모든 요소를 ​​순환하려고하지만 수행하는 동안 배열에서 요소를 삭제한다는 것입니다. 이것은 원래 생각했던 것보다 이제 더 짧은 배열로 인덱싱하려고 시도하고 있으며 모든 인덱스가 변경되고 있음을 의미합니다.

대신 다음 코드를 시도하십시오.

bulletsToRemove = []

if not len(bullets) <= 0:
    for i in range(len(bullets)):
        if bullets[i][1] < 0:
            bulletsToRemove.append(bullets[i])
        else:
            bullets[i][1] -= 5    

for bullet in bulletsToRemove:
    bullets.remove(bullet)

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관