删除副本列表中的消失项目符号
生活随笔
收集整理的這篇文章主要介紹了
删除副本列表中的消失项目符号
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
跟隨我感到困惑的書
這本書說刪除項目符號副本中的項目符號,而不是自己
但是我嘗試兩種效果,真的一樣嗎?
那么這兩個代碼有什么區別?
for bullet in bullets.copy(): if bullet.rect.y <= 0:bullets.remove(bullet)==========================================
for bullet in bullets(): if bullet.rect.y <= 0:bullets.remove(bullet)==========================================
這是整個代碼:
#! /usr/bin/pythonimport pygame as pimport sysclass Setting():def __init__(self,width,height):self.w=widthself.h=heightself.flag=p.RESIZABLEself.color=(255,255,255)self.speed=1self.screen=p.display.set_mode((self.w,self.h),self.flag)p.display.set_caption("Bullet")self.bullet_s=1self.bullet_w=5self.bullet_h=30self.bullet_c=(0,0,0)class Bullet(p.sprite.Sprite):def __init__(self,setting):super().__init__()self.screen_rect=setting.screen.get_rect()self.screen_center=self.screen_rect.centerself.rect=p.Rect((0,0),(setting.bullet_w,setting.bullet_h))self.rect.center=self.screen_centerself.rect.bottom=self.screen_rect.bottomself.color=setting.bullet_cself.speed=setting.bullet_sself.y=float(self.rect.centery)def bullet_check(self,bullets,setting):for event in p.event.get():if event.type == p.QUIT:sys.exit()elif event.type == p.KEYDOWN:if event.key ==p.K_SPACE:bullets.add(Bullet(setting))def move(self):self.y -= self.speedself.rect.y=self.ydef draw(self,setting):p.draw.rect(setting.screen,self.color,self.rect)def bullet_blit(self,bullets,setting):for bullet in bullets.sprites():bullet.draw(setting)bullet.move()for bullet in bullets.copy(): **<-- for bullet in bullets: really same effect**if bullet.rect.y <= 0:bullets.remove(bullet)print(len(bullets)) def game():p.init()setting=Setting(1200,800)bullet=Bullet(setting)bullets=p.sprite.Group() while True:bullet.bullet_check(bullets,setting)setting.screen.fill((255,0,0))bullet.bullet_blit(bullets,setting)p.display.flip() game()解決方案
問題是當您要刪除更多元素并且它們彼此相鄰時。當您刪除第一個元素時,其他元素將移動并for跳過第二個元素-因此,最終它不會刪除所有元素。
這可以正常工作-刪除所有元素,您將獲得空列表?[]
data = ['a', 'a']for x in data.copy():if x == 'a':data.remove(x)print(data)這行不通-跳過一些元素,您將獲得列表?['a']
data = ['a', 'a']for x in data:if x == 'a':data.remove(x)print(data)在python中,使用要保留的元素創建新列表非常流行
data = ['a', 'a', 'b', 'a', 'a']result = []for x in data:if x != 'a':result.append(x)data = resultprint(data)但是可以通過列表理解來縮短
data = ['a', 'a', 'b', 'a', 'a']data = [x for x in data if x != 'a']print(data)總結
以上是生活随笔為你收集整理的删除副本列表中的消失项目符号的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python在for循环中不能删除正在循
- 下一篇: pygame用精灵编组的问题的猜想和验证