Python变量赋值:赋值时更新上一个值

2024-05-23 19:22:29 发布

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

我有一个二维数组,它是从一个文本文件中输入的(这说明我必须将数组中的每个值转换为浮点值)

  while 1:
e=path.find(", ")
#545.423, 169.830 536.723, 164.899 529.696, 160.916 520.343, 157.377 510.990, 153.839 510.298, 153.577
ptx=path[0:e]#545.423
path=path[e+2:]
e=path.find(" ")
if e>0:
  pty=0-float(path[0:e])
  pts.append([ptx,path[0:e]])

我想找出一个值是否出现在数组中的两个连续值之间:

  pta=[None]*2
  ptb=[None]*2
  y=None
  for pt in pts:
    if y==None:
      y=float(pt[1])
      continue
    if pta[0]==None:
      pta[0]=float(pt[0])
      pta[1]=float(pt[1])
      continue
    ptb[0]=float(pt[0])
    ptb[1]=float(pt[1])
    print pta[1],y,ptb[1]
    if (x>pta[0] and x<ptb[0])or(x<pta[0] and x>ptb[0]):
      .... some code ....
    pta=ptb

2D数组的第一个“y值”(它是[x,y]笛卡尔值的数组)分配给“y”,第二个点分配给点“A”(pta),第三个点分配给点“B”,然后点“B”分配给点“A”,新的pt传递给点“B”。打印pta[1],y,ptb[1]的输出如下:

-196.338 -126.302 -196.338
-187.437 -126.302 -187.437
-186.951 -126.302 -186.951
-178.351 -126.302 -178.351
-170.482 -126.302 -170.482
-164.385 -126.302 -164.385
-157.085 -126.302 -157.085
-150.623 -126.302 -150.623
-146.074 -126.302 -146.074
-140.465 -126.302 -140.465
-136.278 -126.302 -136.278
-133.244 -126.302 -133.244

与我预期的不太一样:pta[1]和ptb[1]的值是相同的。我原以为pta[1]和ptb[1]的值是不同的。你知道吗

-125.018 -126.302 -124.258
-124.258 -126.302 -124.007
-124.007 -126.302 -124.272
-124.272 -126.302 -125.045
-125.045 -126.302 -126.302

我需要找到数组中“y”值落在两个数组项之间的位置。你知道吗

我将ptb传递给pta,但是当我将ptb的值更改为数组中的下一个pt时,它似乎也会更改pta?或者在我的代码里有什么我看不见的愚蠢的行?你知道吗


Tags: andpathnoneptif数组findfloat
3条回答

如果我正确理解您的意图,我建议您简化3个连续点的迭代和比较:

pts = [(0,0), (0,1), (0,4), (0,3), (0,2)]
for i in range(len(pts) - 2):
    ax, ay = pts[i]
    bx, by = pts[i + 1]
    cx, cy = pts[i + 2]
    b_between_a_and_c = ay < by < cy
    print("{} is between {} and {}: {}".format(by, ay, cy, b_between_a_and_c))

输出:

1 is between 0 and 4: True
4 is between 1 and 3: False
3 is between 4 and 2: False

当您处理像list这样的可变对象时,不要直接指定它,如下所示

>>> l = [1,2]
>>> b = l
>>> b
[1, 2]
>>> l.append(3)
>>> b
[1, 2, 3]
>>> id(l)
3072560332L
>>> id (b)
3072560332L # both referring to same object, only with different referencing names

一方面的变化可以反映在另一方面。 相反,使用类似于

b = l[:]

它将l复制到b,而不是访问同一个对象。现在两个将有单独的ids。你知道吗

在前3次迭代中,您很可能会看到两个具有不同值的数组:

print pta[1],y,ptb[1]

None, 1, None  # 0
3, 1, None  # 1
3, 1, 6   # 2
4, 1, 4  # on third iteration pta is the same lst as ptb

在第三次迭代中,您正在设置pta=ptb——它们不再像您所希望的那样是不同的lists。一定要这么做

pta=list(ptb)

在你循环的最后。你知道吗

相关问题 更多 >