Reputation: 89
I've been stuck on this for a while. I haven't actually written this code yet, but if I were to it would look something like this;
i = 0 # this is an int I get from somewhere else
s = "" # this is the string that I ultimately want to use for something
if i < 1:
s = "string1"
elif i < 5:
s = "string2"
elif i < 17:
s = "string3"
and so on. Basically I want to assign a different string to assign different strings to different intervals and depending on which interval i falls in, I assign the corresponding string to s.
The example above is really messy and looks like a pain to expand/change. I was thinking this could be somehow solved with a dict, but I can't quite seem to figure it out.
Upvotes: 0
Views: 110
Reputation: 6642
If you define a dictionary with the limit values in the right order you can just pull the next-higher element using a simple generator comprehension:
map_max_string = {1: "string1", 5: "string2", 17: "string3"}
s = next(val for key, val in map_max_string.items() if i < key)
If you don't want to rely on the assumption that the dict is ordered, you can of course still sort it by the key:
s = next(val for key, val in sorted(map_max_string.items())
if i < key)
Upvotes: 1
Reputation: 2273
Since python 3.7 dicts are ordered. So you could define your thresholds as key of a dict and link them to a string:
D = {1: 'string1',
5: 'string2',
17: 'string3'}
x = 10
s = ""
for i in D.keys():
if x < i:
s = D[i]
break
This way you have the definitions close by and save some if
.
Upvotes: 3
Reputation: 461
Without providing any details it's hard to give you any advice. However if you want "pythonic oneliner" here you go:
s = "string1" if i < 1 else ("string2" if i < 5 else "string3")
Upvotes: 0