Python数组正在改变

时间:2016-02-07 06:21:57

标签: python arrays

我的函数将点作为折线,并沿任何直线段移除多个点。

输入的分数如下:

  

pts = [[' 639.625',' -180.719'],[' 629.625',' -180.719' ],[' 619.625',' -180.719'],[' 617.312',' -180.719'],[& #39; 610.867',' -182.001'],[' 605.402',' -185.652'],[' 601.751 ',' -191.117'],[' 600.469',' -197.562'],[' 600.469' ,' -207.562'],[' 600.469',' -208.273']]

  pta=[None]*2
  ptb=[None]*2
  ptc=[None]*2
  simplepts=[]
  for pt in pts:
    if pta[0]==None:
      simplepts.append(pt)
      pta[:]=pt
      continue
    if ptb[0]==None:
      ptb[:]=pt
      continue
    if ptb==pta:
      ptb[:]=pt
      continue
    ptc[:]=pt
    print simplepts#<--[['639.625', '-180.719'], ['605.402', '-185.652']]
    # we check if a, b and c are on a straight line
    # if they are, then b becomes c and the next point is allocated to c.
    # if the are not, then a becomes b and the next point is allocate to c
    if testforStraightline(pta,ptb,ptc):
      ptb[:]=ptc # if it is straight
    else:
      simplepts.append(ptb)
      print simplepts#<--[['639.625', '-180.719'], ['617.312', '-180.719']]
      pta[:]=ptb # if it's not straight

如果该部分不是直的,则ptb会附加到simplepts数组,现在(正确地)[[&#39; 639.625&#39;,&#39; -180.719&#39;], [&#39; 617.312&#39;,&#39; -180.719&#39;]]

但是,在下一次传递中,simplepts数组已更改为[[&#39; 639.625&#39;,&#39; -180.719&#39;],[&#39; 605.402&#39;, &#39; -185.652&#39;]]令人费解。

我认为我的数组中的点只是通过引用保存,而更改其他值会更新数组中的值。

如何确保我的数组值保留指定的值?

谢谢。

1 个答案:

答案 0 :(得分:0)

您在简单中附加了一个列表ptb,然后您正在修改它。不确定您是否可以改进您的设计。但是当前设计的快速解决方案 -

import copy
simplepts.append(copy.deepcopy(ptb))