【问题标题】:How to return the NAME of greater of two variables in python3? [duplicate]如何在python3中返回两个变量中较大的名称? [复制]
【发布时间】:2021-01-07 05:37:07
【问题描述】:

这显然可以通过 if-elif-else 逻辑来完成,但我希望寻求一种更好、更 Python 的方式来实现它。例如。

a,b = 14,73
if a>b:
    print('a')
elif a<b:
    print('b')
else:
    print('a=b') #not_required_though

【问题讨论】:

  • 你可以使用字典
  • 如果您需要变量名,很可能是您的设计存在问题(Keep data out of your variable names。正如@deadshot 提到的 - 例如,您可以使用dict

标签: python python-3.x max


【解决方案1】:

if else 一行可以做

print('a' if a>b else 'b')

或者你也可以把它赋值给变量

res = 'a' if a>b else 'b' if b>a else 'a==b'

【讨论】:

  • 我指的是变量名,而不是变量的值。
猜你喜欢
  • 1970-01-01
  • 2015-12-16
  • 1970-01-01
  • 2020-01-23
  • 1970-01-01
  • 2020-04-08
  • 2016-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多