python - Converting an if/else block with True/False statements into a dictionary -
i iterating through characters in string, , want determine type of each character.
this can done if/else block:
if char.isdigit(): char_type = 'number' elif char.isalpha(): char_type = 'letter' elif char in {'*', '/', '+', '-', '='}: char_type = 'operator' else: char_type = 'other'
if code this:
if val == 1: char_type = 'number' elif val == 2: char_type = 'letter' elif val == 3: char_type = 'operator'
the dictionary be:
d = {1: 'number', 2: 'letter', 3: 'operator'}
but in case, each of statements either true
or false
. can converted dictionary?
yes, can use d[char]
syntax, hardly sees worth cost in complexity , readability.
you encapsulate if/else
in __getitem__
method of class, , use []
syntax retrieve character type, so:
class chartype: def __getitem__(self, char): if char.isdigit(): char_type = 'number' elif char.isalpha(): char_type = 'letter' elif char in {'*', '/', '+', '-', '='}: char_type = 'operator' else: char_type = 'other' return char_type d = chartype() print(d["a"], d["+"])
Comments
Post a Comment