列表的高级比较

时间:2016-03-10 17:45:43

标签: list python-3.x

我目前正在为一个学校项目制定计划,该项目应该帮助农民减少过量施肥(这在丹麦是个大问题)。该程序应该工作的方式是你输入一些关于你的领域的信息(NPK的内容,字段大小,污垢和其他东西的类型),然后我将能够比较他们的领域的营养含量与推荐的量。然后我可以为这个领域创造理论上理想的肥料成分。

这是我能够做到的,但这是困难的部分。

我在丹麦有一长串肥料,我希望我的程序将其中的10种与理论上的理想成分进行比较,然后自动选择最合适的肥料。

我确实没有想法如何做到这一点!

我将肥料成分格式化的方式列在这样的列表中

>>>print(idealfertilizercomp)
[43.15177154944473, 3.9661554732945534, 43.62771020624008, 4.230565838180857, 5.023796932839768]

每个数字代表一个百分比元素。一个例子可能是第一个数字,43.15177154944473,这是我在肥料中需要的钾含量百分比。

TL; DR: 如何创建一个程序或函数,可以将一个整数列表与一个其他整数列表进行比较,然后选择最适合的整数?

1 个答案:

答案 0 :(得分:0)

所以,在我吃饭的时候,我实际想出了一种比较多个列表的方法:

  def numeric(x):
    if x >= 0:
        return x
    else:
        return -x


def comparelists(x,y):
    z1 = numeric(x[0]-y[0])
    z2 = numeric(x[1]-y[1])
    z3 = numeric(x[2]-y[2])
    z4 = numeric(x[3]-y[3])
    z5 = numeric(x[4]-y[4])
    zt = z1+z2+z3+z4+z5
    return zt


def compare2inproportion(x, y, z):
    n1 = (comparelists(x, y))
    n2 = (comparelists(x, z))
    print(n1)
    print(n2)

    if n1 < n2:
        print(y, "is closer to", x, "than", z)
    elif n1 > n2:
        print(z, "is closer to", x, "than", y)
    else:
        print("Both", y, "and", z, "are equally close to", x)

idealfertilizer = [1, 2, 3, 4, 5]
fertilizer1 = [2, 3, 4, 5, 6]
fertilizer2 = [5, 4, 3, 2, 1]

compare2inproportion(idealfertilizer, fertilizer1, fertilizer2)

这只是比较两个列表的基本版本,但它很容易扩展。输出如下:

[2, 3, 4, 5, 6] is closer to [1, 2, 3, 4, 5] than [5, 4, 3, 2, 1]

抱歉花时间,谢谢你的帮助。

相关问题