元组两点直线方程及输出最大值

2024-04-26 09:31:58 发布

您现在位置:Python中文网/ 问答频道 /正文

列表中有元组:

a = [((1, 6), (8, 2)), ((8, 2), (6, 3)), ((6, 3),(9,4))]

我想使用“for”来指定列表中的所有值,例如:

P = [1,6], Q = [8,2] => perform find a straight line, then
P = [8,2], Q = [6,3] => perform find a straight line, then
P = [6,3], Q = [9,4] => perform find a straight line, then

屏幕输出:

PQ1 : y = b1x+c1
PQ2 : y = b2x+c2

最大值d

但我有个错误:

'float' object is not iterable

我不知道在这种情况下如何使用“for”、“function”和“class”

def function(P,Q):
   a = float(P[0]-Q[0])
   b = float(Q[1]-P[1])
   c = float((b*P[0]+a*P[1]))
   d = b/(-a)
   e = (-c)/(-a)
   if d == 0.0 and e == 0.0:
      print("False")
   elif d == 0.0:
      print("Function is y = ",e)
   elif d == 1.0 and e == 0.0:
      print("Function is y = x")
   elif d != 1.0 and e == 0.0:
      print("Function is y = ",d,"x")
   elif d == 1.0 and e > 0:
      print("Function is y = x + ",e)
   elif d == 1.0 and e < 0:
      print("Function is y = x ",e)
   elif e > 0:
      print("Function is y =",d,"x +",e)
   elif e < 0:
      print("Function is y =",d,"x",e)
if __name__ == '__main__': 
   P = [1,6]
   Q = [8,2]
   function(P,Q)

我想使用“for”、“function”和“class”,而不是手工将每个值赋给p和Q,因为元组可以扩展更多

非常感谢


Tags: and列表forislinefunctionfindfloat
1条回答
网友
1楼 · 发布于 2024-04-26 09:31:58

代码:

for P, Q in a:
    function(P, Q)

为什么有效?

  a = [((1, 6), (8, 2)), ((8, 2), (6, 3)), ((6, 3),(9,4))]

如果使用单个变量迭代a,则每次迭代都会将list元素放入该变量。如果在for循环中提供2个变量,python将尝试解包列出元素,如果元素是iterable,并且其元素的计数等于您提供的变量数量,则python将以相同的顺序将值放入变量中。你知道吗

演示代码:

a, b, c, d = (1, 2, 3, 4)  # working
print(a, b, c, d)
a, b, c, d = [1, 2, 3, 4]  # working
print(a, b, c, d)
a, b, c, d = {1, 2, 3, 4}  # working
print(a, b, c, d)
a, b, c, d = "1234"        # working
print(a, b, c, d)
a, b, c, d = range(1, 5)   # working
print(a, b, c, d)
a, b, c, d = (1, 2)        # error

相关问题 更多 >