首页 > 解决方案 > 我无法在 python 的嵌套列表中找到重复的元素。如果有人有最好的解决方案?

问题描述

列表列表的前三行(如下所示),然后“alfa-romero”有 2 个“convertible”类型,“alfa-romero”有一个“掀背车”。

我有这个嵌套列表,作为输入

cars = [['alfa-romero', 'convertible'],
['alfa-romero', 'convertible'],
['alfa-romero', 'hatchback'],
['audi', 'sedan'],
['audi', 'sedan'],
['audi', 'sedan'],
['audi', 'sedan'],
['audi', 'wagon'],
['audi', 'sedan']]

因此,您的输出应该是一个列表列表,例如输出将是这样的

[‘alfa-romero --- convertible’, 2]
[‘alfa-romero --- hatchback’, 1]
[‘audi --- sedan’,4]

标签: pythonpython-3.xlist

解决方案


我建议使用字典。指定的选择输出不是显示数据的最合适方式。过滤掉列表的一种方法是:

cars = [['alfa-romero', 'convertible'],
['alfa-romero', 'convertible'],
['alfa-romero', 'hatchback'],
['audi', 'sedan'],
['audi', 'sedan'],
['audi', 'sedan'],
['audi', 'sedan'],
['audi', 'wagon'],
['audi', 'sedan']]

cars_dict = {}
for car in cars: # loop through each car
    if not(car[0] in list(cars_dict.keys())): # if the make has not occurred before make dictionary
        cars_dict[car[0]] = {}
        cars_dict[car[0]][car[1]] = 1
    else:
        if car[1] in list(cars_dict[car[0]].keys()):
            cars_dict[car[0]][car[1]] += 1
        else: 
            cars_dict[car[0]][car[1]] = 1 #if the type has not occurred before than make dictionary
print(cars_dict)

哪个输出:

{'alfa-romero': {'convertible': 2, 'hatchback': 1}, 'audi': {'sedan': 5, 'wagon': 1}}

即字典词典。由 car_dict[maker][type] 访问。第一个字典的键是汽车的品牌,第二个字典的键是汽车的类型。

如果需要以您指定的格式输出,您可以使用以下命令将 cars_dict 字典转换为 required_output 列表:

required_output = []
for maker in cars_dict.keys():
    for type_of_car in cars_dict[maker].keys():
        required_output.append([str(maker) + " --- " + str(type_of_car), cars_dict[maker][type_of_car]])
print(required_output)

推荐阅读