我想创建一个可用于删除非常用元素的函数(我应该删除奥迪的两个清单的梅赛德斯):
marcas = [
(1, 'Audi'),
(2, 'Nissan'),
(3, 'Mercedes'),]
marcas2 = []
coches = [
{
'modelo': 'Audi C3',
'marca': 1,
'precio': 25000,
'ano': 2017,
}]
def delbrand(marcas):
for y in coches:
for x in marcas:
if y['marca'] == x[0]:
if x not in marcas2:
marcas2.append(x)
m = 0
for i in marcas:
if i not in marcas2:
del marcaslist[m]
m = m+1
您愿意帮我解决这个问题吗?
答案 0 :(得分:0)
不清楚您要什么。我对您的代码做了一些修改:
brands = ['Audi', 'Nissan', 'Mercedes']
cars = [
{
'modelo': 'Audi C3',
'marca': 1,
'precio': 25000,
'ano': 2017,
}]
not_existing_brands = set()
def find_not_common(brands, cars):
for brand in brands:
for car in cars:
if brand not in car['modelo']:
not_existing_brands.add(brand)
find_not_common(brands, cars)
print brands
print list(not_existing_brands)
for item in list(not_existing_brands):
brands.remove(item)
# final brands list
print brands
输出:
['Audi', 'Nissan', 'Mercedes']
['Mercedes', 'Nissan']
['Audi']