Создайте массив значений в операторе if в Python

#python

#python

Вопрос:

Я хочу создать массив значений на основе условия.

 data_total = [
    {"modele": "DS",
     "cote_actual": 10000},
    {"modele": "DS",
     "cote_actual": 12000},
    {"modele": "204",
     "cote_actual": 10000}]

for total in data_total:
    model = total["modele"]
    cote_actual = total["cote_actual"]
    model_ds = []

    if model == "DS":
        model_cote = cote_actual
        print(model_cote)
        model_ds.append(model_cote)
        print(model_ds)
 

Результат, который я хочу:

 "modele_ds" = [10000, 12000]
 

Я путаюсь с циклом, у меня нет нужных мне входных данных. Я знаю, что мне нужно добавить или заполнить массив.

Комментарии:

1. Вы назначаете новый пустой список model_ds на каждой итерации цикла, я не думаю, что это то, чего вы хотите

2. Следуя @UnholySheep, вы должны определить model_ds вне цикла, если это еще не было ясно.

Ответ №1:

Как говорили другие, вы должны назначить список model_ds вне цикла, потому что, имея его внутри цикла, он становится пустым с каждой итерацией. Ваш код должен быть (строка, которая была изменена, с комментарием):

 data_total = [
    {"modele": "DS",
     "cote_actual": 10000},
    {"modele": "DS",
     "cote_actual": 12000},
    {"modele": "204",
     "cote_actual": 10000}]

model_ds = [] #assign model_ds outside the loop
for total in data_total:
    model = total["modele"]
    cote_actual = total["cote_actual"]
    if model == "DS":
        model_cote = cote_actual
        model_ds.append(model_cote)
 

Вывод:

 >>> print(model_ds)

[10000, 12000]
 

Ответ №2:

 [ x['cote_actual'] for x in data_total if x['modele'] == 'DS‘]
 

Ответ №3:

ниже

 data_total = [
    {"modele": "DS",
     "cote_actual": 10000},
    {"modele": "DS",
     "cote_actual": 12000},
    {"modele": "204",
     "cote_actual": 10000}]

lst = [e['cote_actual'] for e in data_total if e['modele'] == 'DS']
print(lst)
 

вывод

 [10000, 12000]