【问题标题】:I want to delete non comon items of two lists我想删除两个列表的不常见项目
【发布时间】:2019-05-24 20:37:15
【问题描述】:

我想创建一个可用于删除非常见元素的函数(我应该删除两个列表的奥迪和梅赛德斯):

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

你介意帮我解答这个问题吗?

【问题讨论】:

标签: python python-3.x


【解决方案1】:

目前还不是很清楚你在问什么。我稍微修改了你的代码:

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']

【讨论】:

  • 非常感谢,我需要在品牌列表中删除汽车列表中没有的品牌(梅赛德斯和日产)。
  • 我根据您的要求更新了代码。如果您认为我的回答对您的需求有帮助,请勾选绿色;)
猜你喜欢
  • 1970-01-01
  • 2019-07-15
  • 1970-01-01
  • 2017-03-15
  • 2019-06-23
  • 1970-01-01
  • 2023-01-27
  • 2020-08-23
  • 2021-05-31
相关资源
最近更新 更多