重复后Python列表更改索引值为1

时间:2015-06-29 23:40:46

标签: python list variables reference variable-assignment

作为一个假设的例子:

<div ng-controller="ClientCtrl as clients">
  <table class="listview">
    <tbody>
      <tr ng-repeat="stuff in clients.records">
        <td>
          <a ng-click="clients.client =  $index" class="client-link">{{stuff.first_name}} {{stuff.last_name}}</a>
        </td>
      </tr>
    </tbody>
  </table>
  <div class="detailview">
    <div ng-repeat="things in clients.records ">
      <div id="contact-{{$index}}" class="tab-pane active" ng-show="clients.client == $index" ng-init="clients.client = $index">
        <h2>{{things.first_name}} {{things.last_name}}</h2>
      </div>
    </div>
  </div>
</div>

我知道这是因为对>>> a = [1, 2, 3] >>> b = a >>> b[0] = 4 >>> b [4, 2, 3] >>> a [4, 2, 3] a的引用是相同的,因此指向相同的内存字节。 b引用的字节数变化将反映在b中,因为它们共享相同的内存。

解决此问题的最佳方法是什么,以便a保持原始价值,ab生成后,对a的更改不会转到b,也是。

具体代码:

a

返回:

outputs = []
a = [[0,2,5],[4,2,0],[6,0,0]]
for i in range(3):
  for j in range(3):
    if not a[i][j]:
      b = a
      b[i][j] = 1
      outputs.append(b)

2 个答案:

答案 0 :(得分:1)

您可以通过切片来复制原始列表:

a = [1, 2, 3]
b = a[:]

或者使用内置列表list()函数:

b = list(a)

您也可以使用列表推导代替嵌套的for循环:

b = [[i if i else 1 for i in j] for j in a]

答案 1 :(得分:0)

这:

new_list = list(old_list)

所以这会发生 -

>>> a = [1,2,3]
>>> b = list(a)
>>> b.append(8)
>>> b
[1, 2, 3, 8]
>>> a
[1, 2, 3]