最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Use greaterequalless comparison result as dictionary key - Stack Overflow

programmeradmin2浏览0评论

Is there a clean way to store the values comparison result as dictionary key, naming >, =, and < (not the str format, but the state of "greater" for example).

Curious if this could be a way to replace wordy

if a > b:
    print(f'{a} > {b}')
elif a == b:
    print(f'{a} = {b}')
else:
    print(f'{a} < {b}')

with a dict

d = {
    >: '{a} > {b}',  # > is something I don't know how to use, not str('>')
    =: '{a} = {b}',
    <: '{a} < {b}',
}

Then I can use it like

compare_result = a > b  # I know this returns boolean; I need a way to return a comparison result in one of {>, =, <}
print(d[compare_result].format(a, b))

something like that.

Is there a clean way to store the values comparison result as dictionary key, naming >, =, and < (not the str format, but the state of "greater" for example).

Curious if this could be a way to replace wordy

if a > b:
    print(f'{a} > {b}')
elif a == b:
    print(f'{a} = {b}')
else:
    print(f'{a} < {b}')

with a dict

d = {
    >: '{a} > {b}',  # > is something I don't know how to use, not str('>')
    =: '{a} = {b}',
    <: '{a} < {b}',
}

Then I can use it like

compare_result = a > b  # I know this returns boolean; I need a way to return a comparison result in one of {>, =, <}
print(d[compare_result].format(a, b))

something like that.

Share Improve this question edited Apr 1 at 9:57 mkrieger1 23.4k7 gold badges64 silver badges82 bronze badges asked Apr 1 at 0:40 DysonDyson 1251 silver badge12 bronze badges 2
  • See also: stackoverflow/questions/22490366/how-to-use-cmp-in-python-3 – mkrieger1 Commented Apr 1 at 9:57
  • Why insist on a dictionary? I'd do this without one, but now I can't post that as an answer. – Kelly Bundy Commented Apr 1 at 12:31
Add a comment  | 

4 Answers 4

Reset to default 1

The operator module contains actual function objects for greater-than, less-than, equal, etc.

import operator

d = {
    operator.gt: '{a} > {b}',
    operator.eq: '{a} = {b}',
    operator.lt: '{a} < {b}',
}

You could define an enum class:

from enum import Enum, auto

class Comparison(Enum):
    LESS = auto()
    EQUAL = auto()
    GREATER = auto()

def compare(a, b) -> Comparison:
    if a < b:
        return Comparison.LESS
    elif a > b:
        return Comparison.GREATER
    else:
        return Comparison.EQUAL

_TEMPLATE_BY_COMPARISON = {
    Comparison.LESS:  '{a} < {b}',
    Comparison.EQUAL: '{a} = {b}',
    Comparison.GREATER: '{a} > {b}',
}

a, b = 3, 7
result = compare(a, b)
print(_TEMPLATE_BY_COMPARISON[result].format(a=a, b=b))

Output:

3 < 7

You could do a trick by modifying condition something like this to make it easy.

def compare(a, b):
    # create a mapping of comparisons to their template
    comparison_dict = {
        (True, False): "{a} > {b}",  # >
        (False, True): "{a} < {b}",  # <
        (False, False): "{a} = {b}",  # ==
    }
    # based on the values of a > b and a < b, the appropriate key in the dictionary is chosen
    return comparison_dict[(a > b, a < b)]


# example =
a, b = 50, 50
print(compare(a, b).format(a=a, b=b))

# example <
a, b = 10, 50
print(compare(a, b).format(a=a, b=b))

# example >
a, b = 50, 10
print(compare(a, b).format(a=a, b=b))

Can write something like:

def sign(x):
    return abs(x)/x if x != 0 else 0

d = {
    1: f"{a} > {b}",
    0: f"{a} = {b}",
    -1: f"{a} < {b}"
}

As an example:

a = 5
b = 3
print(d[sign(a - b)].format(a=a, b=b))

outputs

5 > 3
发布评论

评论列表(0)

  1. 暂无评论