Skip to content
Advertisement

How can I Iterate through lists, without calling each list individually – in Python

I have the following arrays:

x=-1
y=1
a11 = [x,1]
a12 = [y,1]
a13 = [x,2]
a21 = [y,1]
a22 = [x,2]
a23 = [y,2]
a31 = [x,1]
a32 = [y,2]
a33 = [x,2]

And I need to run each array through the following if-else statement:

votes_1 = []
votes_2 = []
if a11[1] == 1:
  votes_1.append(a11[0])
else:
  votes_2.append(a11[0])

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.

x=-1
y=1
a = [
    [x,1],
    [y,1],
    [x,2],
    [y,1],
    [x,2],
    [y,2],
    [x,1],
    [y,2],
    [x,2],
]

votes_1 = [i for i, j in a if j == 1]
votes_2 = [i for i, j in a if j != 1]

You can do the same thing with votes. For example:

votes = {
    v: [i for i, j in a if j == v]
    for v in (1, 2)
}

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement