比较列表以查看答案是低还是高

时间:2013-06-04 03:40:37

标签: python list if-statement comparison

第一部分产生

    average = ['2 is the average for mark a', 
       '1 is the average for mark b', 
       '1 is the average for mark c',
       '2 is the average for mark d', 
       '1 is the average for mark e', 
       '1 is the average for mark f', 
       '1 is the average for mark g', 
       '1 is the average for mark h', 
       '1 is the rainfall average for mark i',
       '1 is the average for mark j']

然后代码的第二部分产生

z = [1.2423] 

我现在尝试将平均值的结果与z列表进行比较并生成结果。基本上

if the integer value for a is greater than z then print greater than
if the integer value for b is less than z the print less than   
if the integer value for c is greater than z the print greater than.

有没有办法简单地使用我的代码,以便比较所有平均值而无需为每个代码手动输入if语句?即比较所有平均值,然后在平均值小于或大于一行时打印。

感谢。这是我今天的最后一个问题。

2 个答案:

答案 0 :(得分:0)

您在这里提供的“几乎没有”信息可以解决您的问题。此外,一些进一步的研究不会误入歧途。你会到达那里。坚持下去。

average = [a list of your data averages]
z = 1.2423 # z variable doesn't need to be a list, just an int


for i in average:
   if int(i) > z:
       print "greater than"
   elif int(i) < z:
       print "less than"
   else:
       print "equal to z"

答案 1 :(得分:0)

>>> z = 1.2423
>>> [{-1: 'less than', 0: 'equal to', 1: 'greater than'}[(x > z) - (x < z)] for x in [1, 1, 2, 1, 1, 2, 2]]
['less than', 'less than', 'greater than', 'less than', 'less than', 'greater than', 'greater than']

如果您运行的是2.x,那么方括号中的数学运算可以替换为cmp(x, z)