python - 我无法在 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]
解决方案
我建议使用字典。指定的选择输出不是显示数据的最合适方式。过滤掉列表的一种方法是:
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)
推荐阅读
- css - 使用 CSS 禁用鼠标滚轮缩放
- typescript - 条件类型在 TypeScript 中是如何工作的
- android - 如何将android项目导入flutter项目
- azure - “错误:对象已被处置”是什么意思?- 用于 Javascript 的 Microsoft 语音 SDK
- python - 给定条件更改 numpy 子数组中所有元素的值
- r - 具有 nlme 和 lme4 的线性混合模型中的多重随机效应
- python - 过滤日期时间字段python
- google-chrome - 量角器 - 错误代码 199:Chrome 版本不支持 84 版
- c - C中的浮点异常(核心转储)
- typo3 - TYPO3 多个嵌套的 DatabaseQueryProcessor