I want to create an array of values based on a condition.
JavaScript
x
19
19
1
data_total = [
2
{"modele": "DS",
3
"cote_actual": 10000},
4
{"modele": "DS",
5
"cote_actual": 12000},
6
{"modele": "204",
7
"cote_actual": 10000}]
8
9
for total in data_total:
10
model = total["modele"]
11
cote_actual = total["cote_actual"]
12
model_ds = []
13
14
if model == "DS":
15
model_cote = cote_actual
16
print(model_cote)
17
model_ds.append(model_cote)
18
print(model_ds)
19
The output I want:
JavaScript
1
2
1
"modele_ds" = [10000, 12000]
2
I mess with the loop, I don’t have the input I need. I know I have to append or populate the array.
Advertisement
Answer
As others said, you must assign model_ds list outside the loop, because having it inside the loop it gets empty with every iteration. Your code should be (line that changed is with comment):
JavaScript
1
16
16
1
data_total = [
2
{"modele": "DS",
3
"cote_actual": 10000},
4
{"modele": "DS",
5
"cote_actual": 12000},
6
{"modele": "204",
7
"cote_actual": 10000}]
8
9
model_ds = [] #assign model_ds outside the loop
10
for total in data_total:
11
model = total["modele"]
12
cote_actual = total["cote_actual"]
13
if model == "DS":
14
model_cote = cote_actual
15
model_ds.append(model_cote)
16
Output:
JavaScript
1
4
1
>>> print(model_ds)
2
3
[10000, 12000]
4