我的列表中有元组:
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
但是我有错误:
“浮动”对象不可迭代
在这种情况下,我不知道如何使用“”,“功能”和“类”
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)
我想使用“代表”,“功能”和“类”,而不是手动将每个值分配给P和Q,因为元组可以扩展更多
非常感谢您
答案 0 :(得分:0)
代码:
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将尝试解压缩列表元素,如果element是可迭代的并且其元素数等于您提供的变量数量, ll将值按相同顺序放入变量。
演示代码:
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