+-
在Python中定义函数时如何调用列表?
我事先表示歉意.我是编码的初学者.

我正在尝试使用Python使用以下代码编写一个函数,以使用包含节点位置的2个列表来计算多边形的面积:

def Area(xvalues, yvalues):
    area = 0
    stepone = 0
    for x in xvalues:
        for y in yvalues:
            stepone = stepone + (xvalues(x)-xvalues(0))*(yvalues(y+1)-yvalues(y-1))
            area = abs(stepone)/2
    print area

xvalues = [2000, 2126, 2716, 2524, 2518, 2000]
yvalues = [1000, 1256, 1102, 408, 611, 1000]

Area(xvalues, yvalues)

但是,我收到一条错误消息,指出“ TypeError:’列表’对象不可调用”.

我只希望方程式在列表中循环并返回最终产品.我不确定哪里出错了,但是我认为这可能与我的函数参数有关.

任何帮助将不胜感激.

最佳答案
您尝试在此处致电:xvalues(x).如果x是一个索引,则希望xvalues [x]带方括号而不是括号,但是x本身就是元素!但是,看起来您正在尝试访问的元素与从迭代器中获取的元素不同.您可以在范围(len(xvalues))中循环x,如下所示:

def Area(xvalues, yvalues):
    area = 0
    stepone = 0
    for x in range(len(xvalues)):
        for y in range(len(yvalues)):
            stepone = stepone + (xvalues[x]-x[0])*(yvalues[y+1]-yvalues[y-1])
            area = abs(stepone)/2
    print area

但是它有几个问题.首先,在y为0的情况下,yvalues [y-1]不能给您期望.​​但是我不知道您希望从中得到什么.我能猜到的最好的是:

def Area(xvalues, yvalues):
    area = 0
    stepone = 0
    firstx = xvalues[0]
    for x in xvalues:
        for y1, y2 in zip(yvalues[1:], yvalues[:-1]):
            stepone = stepone + (x-firstx)*(y1-y2)
            area = abs(stepone)/2
    print area

该zip会创建一个新列表,对其进行迭代,然后将y1和y2分配给以下元素:[[1256,1000),(1102,1256),(408,1102),(611,408),(1000,611 )]

点击查看更多相关文章

转载注明原文:在Python中定义函数时如何调用列表? - 乐贴网