Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中类对象的列表_Python_List_Class - Fatal编程技术网

python中类对象的列表

python中类对象的列表,python,list,class,Python,List,Class,我有一个这样定义的类 class a: x=Null y=[] 我有一张a类物品的清单 list=[] 我有一个函数,它用class对象附加列表 start(str,price): obj=a() obj.x=str obj.y.append(price) list.append(obj) 我多次调用这个函数 start("x1",10) start("y1",20) start("z1",30) start("x1",100) for

我有一个这样定义的类

class a:
   x=Null
   y=[]
我有一张a类物品的清单

list=[]
我有一个函数,它用class对象附加列表

start(str,price):
     obj=a()
     obj.x=str
     obj.y.append(price)
     list.append(obj)
我多次调用这个函数

start("x1",10)
start("y1",20)
start("z1",30)
start("x1",100)
for i in range(0,len(list))
   print(list[i].x)
   print(list[i].y)

现在列表中的obj.y也将所有的价格附加到了它后面

是否有其他方法来满足此要求

我只想将一个x1附加到列表中,对象的x属性没有重复项,但它应该只附加到早期的x1对象列表中,也只将x1的价格附加到x1.y

实际产出

x1
[10,20,30,100]
y1
[10,20,30,100]
z1
[10,20,30,100]
x1
[10,20,30,100]
预期op

x1
[10,100]
y1
[20]
z1
[30]


请在下面的代码中查看我的回答。这就是我如何实现它以实现您的输出目标的第一眼。出于您的目的,我建议您使用字典方法,而不是将每个键值存储在其自己的类对象中(除非您想执行查询中未声明的重载之类的操作)。希望有帮助,干杯

class test:

    master_dict = {} 

    def __init__(self):
        pass 

    def add_data(self,str,price):
        # function / routine to add data to master_dict
        # str is key, price is value 

        # search if str is part of existing keys to avoid duplication of key
        if str in self.master_dict.keys():
            print("Key already exists. Skipping initialization...") # you can comment this out
            self.master_dict[str].append(price) 
        else:
            # lets init with empty list 
            print("Allocating empty list...") # you can comment this out
            self.master_dict[str] = [] # initialize list 'container' here
            self.master_dict[str].append(price) 

if __name__ == "__main__":

    # only do this once. Don't keep making an instance of the class
    # if its unnecessary 
    a = test() 

    # then add your data using the method 
    a.add_data('x1', 10)
    a.add_data('x1', 100)
    a.add_data('y1', 20)
    a.add_data('z1', 30)

    # lets check
    for key,value in a.master_dict.items():
        print(key,value)
您将获得输出(您可以注释掉不必要的打印)


给你的类一个
\uuuu init\uuu
并在其中初始化
y
。实际输出的原因是有一个单独的a.y,你要在其中添加数字。顺便说一句,不要像list和str那样命名变量。你最好使用
Dict[str,list[int]
。创建一个字典,它的
是“str”,而
是一个“price”列表。如果您完成了字典,将字典转换为对象列表是非常容易的。为此,请使用字典,除非您以后想在类中执行一些时髦的重载操作……请参阅下面的答案
Allocating empty list...
Key already exists. Skipping initialization...
Allocating empty list...
Allocating empty list...
x1 [10, 100]
y1 [20]
z1 [30]