gpt4 book ai didi

python - newList = 列表 - 自身

转载 作者:行者123 更新时间:2023-12-01 06:27:12 26 4
gpt4 key购买 nike

我有一个称为字符的对象列表,如下所示:

characters=[character(0,0,20,20,keys1),character(50,50,50,50,keys2),character(200,200,100,20,keys1)]

其中字符类定义为:

class character():
def __init__(self,x,y,w,h,keys=keys1):
self.x = x
self.y = y
self.w = w
self.h = h
self.keys = keys
self.vel = 200 /math.sqrt(self.w*self.h)
self.crashed=False
# I need an list to use here in a function of my "character" class


# my list must have all the elements in my initial list but self

我的意思是像

characters[0].myFunction() 必须具有 [characters[1],characters[2]] 列表 这是 characters =[character(50,50,50,50,keys2),character(200,200,100,20,keys1)]

最佳答案

您必须将完整列表作为参数传递给 .myFunction 才能知道从哪个列表中排除/过滤 self:

class character():

def __init__(self,x,y,w,h,keys=keys1):
self.x = x
self.y = y
self.w = w
self.h = h
self.keys = keys
self.vel = 200 /math.sqrt(self.w*self.h)
self.crashed = False

def __repr__(self):
return 'charcter({}, {}, {}, {}, {})'.format(
self.x, self.y, self.w, self.h, self.keys)

def myFunction(self, characters):
return [e for e in characters if e != self]

print(characters[0].myFunction(characters))

输出:

[charcter(50, 50, 50, 50, keys2), charcter(200, 200, 100, 20, keys1)]

关于python - newList = 列表 - 自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60078012/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com