Python: 同时检查三个变量的值

Python: Checking for the values of three variables at the same time

我有三个随机生成的浮点数,a、b 和 c:

a = np.random.uniform(-99.999, 99.999)
b = np.random.uniform(-99.999, 99.999)
c = np.random.uniform(-99.999, 99.999)

我想 return 它们采用以下格式:

         1         2         3         4         5         
123456789012345678901234567890123456789012345678901234567
#########################################################RULER

SOMETHING ELSE  ~   ~   ~   ~    -XX.XXX -XX.XXX -XX.XXX

现在我需要一种方法来检查:

因此变量 a、b 和 c 的每个值都可以是(正或负)和(大于 10 或小于 10),目标是始终将数字写入完全相同的位置(由 [=37 调整) =]s).

问题到此为止。

我的 python 知识还很基础。我要做的,可能会涉及到 50 多行代码,包括...

if x >= 0 and x // 10 != 0: #check if x is larger than 0 and has two digits
   if y >= 0 and y // 10 != 0: #check if y is larger than 0 and has two digits 
      ...

但必须有一个更优雅的解决方案,甚至可能是一个班轮。

这是组合三个 if 语句的一种方法。你可以为你的任务扩展这个想法

x, y, z = 12, 24, 16

if all(item > 0 and item // 10 != 0 for item in [x,y,z]):
    print ("Condition matched")
else:
    print ("Condition not matched")

# x, y, z = 12, 24, 16
# Condition matched

# x, y, z = 12, 24, 6
# Condition not matched

我将这个问题解释为 "I want to convert each of my floats into a string, adding however many spaces is necessary to make them exactly seven spaces long"。

您实际上不需要 任何 条件。 str.format 方法可以将填充应用于您的值,而无需计算小数位数或任何其他内容。

>>> a = 1.0
>>> b = -23.42
>>> c = 5.678
>>> result = "{: 7} {: 7} {: 7}".format(a,b,c)
>>> print(result)
    1.0  -23.42   5.678

如果您正在考虑 "ok, but I also want the number to display exactly three digits after the decimal point, even if they're zeroes," 那么您可以这样做:

>>> "{:7.3f} {:7.3f} {:7.3f}".format(a,b,c)
'  1.000 -23.420   5.678'

如果您正在考虑 "ok, but I also want the padding to appear after the sign but before the digits," 那么您可以这样做:

>>> a = -1.0
>>> "{:=7.03f} {:=7.03f} {:=7.03f}".format(a,b,c)
'- 1.000 -23.420   5.678'

如果您正在考虑 "ok, but can the padding be zeroes instead of spaces? So then every number has exactly two digits before the decimal point",那么您可以这样做:

>>> "{:0= 7.03f} {:0= 7.03f} {:0= 7.03f}".format(a,b,c)
'-01.000 -23.420  05.678'