I have the following arrays:
JavaScript
x
12
12
1
x=-1
2
y=1
3
a11 = [x,1]
4
a12 = [y,1]
5
a13 = [x,2]
6
a21 = [y,1]
7
a22 = [x,2]
8
a23 = [y,2]
9
a31 = [x,1]
10
a32 = [y,2]
11
a33 = [x,2]
12
And I need to run each array through the following if-else statement:
JavaScript
1
7
1
votes_1 = []
2
votes_2 = []
3
if a11[1] == 1:
4
votes_1.append(a11[0])
5
else:
6
votes_2.append(a11[0])
7
How can I do this without writing an if-else statement for each array? It’s manageable for now, but I plan to have 25 of these arrays, and I feel like there’s a better way.
Advertisement
Answer
Put all of your votes into a list instead of in 25 different named variables.
JavaScript
1
17
17
1
x=-1
2
y=1
3
a = [
4
[x,1],
5
[y,1],
6
[x,2],
7
[y,1],
8
[x,2],
9
[y,2],
10
[x,1],
11
[y,2],
12
[x,2],
13
]
14
15
votes_1 = [i for i, j in a if j == 1]
16
votes_2 = [i for i, j in a if j != 1]
17
You can do the same thing with votes
. For example:
JavaScript
1
5
1
votes = {
2
v: [i for i, j in a if j == v]
3
for v in (1, 2)
4
}
5
Now votes[1]
and votes[2]
have the same contents as votes_1
and votes_2
in the earlier version of the code, but you can expand this to cover any number of different voting options just by changing that for v in (1, 2)
line.