jeudi 8 octobre 2020

Python 3 conditional variable selection increment

I'm currently working on a project where a lot of different accounting is done and I came to see this pattern very often:

if A > X:
    B += 1
else:
    C += 1

I know ternary operator but if I understand it correctly the shortest way how to utilize it would be:

B += 1 if A > X else False
C += 1 if A <= X else False

since ternary operator is connected to the variable used in its head. So using ternary operator is obviously worse than the previous if/else both from computational and readability standpoint.

The other idea was to create a simple function like this:

conditional_bumper(positive_case_var, negative_case_var, condition_var, compare_to=0)

then the usage looks like:

conditional_bumper(B, C, A, X)  # X being optional

so I can one line it every time I see it but at the same time this seems to me like a very 'hacky' solution. Is there a better way I don't see?

Aucun commentaire:

Enregistrer un commentaire