Python 嵌套 for 循环

Python nested for loops

car_list=[['BMW',4,False,200],['Mercedes',3,False,250],['Renault',2,False,150],['Audi',3,False,180]] #car list

new_list=[] 
def add_new_car(horsepower,brand,car_list):
    for lists in car_list:
        for i in lists:
            if brand==i :
                lists[1]=lists[1]+1
                print(car_list)

            else: #from there i dont want to execute program when brand is mercedes. if brand is different from list i want to execute . but program executes.:$$
                if brand != i:
                    new_list.append(brand)
                    new_list.append(1)
                    new_list.append(True)
                    new_list.append(horsepower)
                    car_list.append(new_list)
                    print(car_list)
                    break
        break

brand='Mercedes' #when brand is mercedes program executes else if part and creates new list and add this lst to car list. but i cant add it to existed mercedes list as> mercedes,3,false,250 
horsepower=170

add_new_car(horsepower,brand,car_list)

我的代码无法正常工作。当品牌是 mercedes 时我不能做这件事它执行 else if 部分并创建新列表..但我想将它添加到现有的 mercedes 列表..新列表将是

[['BMW',4,False,200],['Mercedes',4,False,250],['Renault',2,False,150],['Audi',3,False,180]]

没有

[['BMW', 4, False, 200], ['Mercedes', 3, False, 250], ['Renault', 2, False, 150], ['Audi', 3, False, 180], ['Mercedes', 1, True, 170]]

我能为它做什么?

您不需要遍历内部列表。该循环就是原因,您将为每个输入分配 else if 部分。只需用 lists[0] 索引值检查 brand 值。

我想下面的功能应该足够了。要将 brand 添加到列表中(如果它不存在),您可以使用 for 循环的 else 部分,该部分在循环完成但没有 break 时执行。

def add_new_car(horsepower,brand,car_list):
    for lists in car_list:
        if lists[0] == brand:
            lists[1] = lists[1]+1
            break
    else:
        cart_list.append([brand, 1, True, horsepower])

此代码适用于您 İlayda。您不需要添加内部 for 循环,并且在 for 循环之后放置 else 保证在没有匹配项时添加新项。

car_list = [['BMW', 4, False, 200], ['Mercedes', 3, False, 250], ['Renault', 2, False, 150], ['Audi', 3, False, 180]]

def add_new_car(horsepower, brand, car_list):
    for lists in car_list:
        if lists[0] == brand:
            lists[1] += 1
            break
    else:
        new_list = []
        new_list.append(brand)
        new_list.append(1)
        new_list.append(True)
        new_list.append(horsepower)
        car_list.append(new_list)

brand = 'Mercedes'
horsepower = 170

add_new_car(horsepower, brand, car_list)
print car_list