找出一个数字的更多pythonic方法对所有数字都是最小的

NIl*_*rma 0 python compare max minimum

是否有任何pythonic方法可以找出变量具有一堆变量中的最小值.例如

In [5]: if d<c and d<b and d<a:
   ...:     print "d is minimum.."
   ...:     
d is minimum..
Run Code Online (Sandbox Code Playgroud)

现在这里只有3个变量,所以我们可以用它来做,但是如果有那么多的变量需要比较呢?
请告诉我一次检查d的情况是否与所有其他变量一起最大.
检查d 等于所有其他变量怎么样?
我的解决方案

可能我们可以添加需要在列表中进行比较的所有变量并逐个进行比较,但我认为必须有更好的方法来使用python进行此操作.

Jon*_*nts 8

使用all哪个会有效,因为它会短路:

if all(d < i for i in [1,5,4,4,6,6,4,4,5]) 
Run Code Online (Sandbox Code Playgroud)

哪里i可以是任何可迭代的

你的例子是:

if all(d < i for i in (c, b, a))
Run Code Online (Sandbox Code Playgroud)

  • *唱*"这些东西中的一个与其他东西不一样......"(好的方式(+1)) (2认同)

mgi*_*son 5

你看过这个min功能了吗?

if d <= min(c,b,a):
   ...
Run Code Online (Sandbox Code Playgroud)

当然,您也可以使用iterable:

if d <= min([c,b,a]):
   ...
Run Code Online (Sandbox Code Playgroud)

我喜欢这个版本,因为它是明确的.它很容易阅读.正如JonClements指出的那样,对于大型集合,可能有更有效的方法.