按对象属性拆分对象列表

时间:2020-04-18 16:44:39

标签: python-3.x list collections split

我无法弄清楚如何按对象值分割对象列表。 例如:

class car:
    cid=0
    type="undef"

    def  __init__(self, cid,type):
        self.cid=cid
        self.type=type

    def show(self):
        print("car id : "+str(self.cid)+" car type : "+self.type)

car_list=[]
car_list.append(car(34,"Suv"))
car_list.append(car(47,"Suv"))
car_list.append(car(48,"Suv"))
car_list.append(car(42,"hb"))
car_list.append(car(40,"hb"))
car_list.append(car(37,"sed"))
car_list.append(car(77,"sed"))
car_list.append(car(22,"sed"))

我想将car_list分成每种类型的汽车列表。然后在列表前打印汽车的类型。 预期输出:

SUV
==========================
car id : 34 car type : Suv
car id : 47 car type : Suv
car id : 47 car type : Suv
HB
==========================
car id : 47 car type : hb
car id : 47 car type : hb
SED
==========================
car id : 47 car type : sed
car id : 47 car type : sed
car id : 47 car type : sed

2 个答案:

答案 0 :(得分:0)

U可以首先创建类型列表,例如types = ['SUV', 'HB', 'SED']或使用循环从列表中搜索类型:

types = []
for car in car_list:
    if not car.type in types:
        types.append(car.type)

最后,再次循环以获取相同的类型:

for type in types:
    print(type.upper())
    for car in car_list:
        if car.type.lower() == type.lower():
            car.show()

答案 1 :(得分:0)

想通了:

from collections import groupby 
grouped_car_list= groupby(car_list, key = lambda car : car.type)

for  type , cars in grouped_car_list:
    print(type)
    print("=============================")
    for car in cars:
        car.show()

相关问题