python : Appending Integer array in list while iterating

标签 python arrays iteration

我有一个整数数组 offset=array('i',[0,0])

off=[]
offset=array('i',[0,0])
for each in [1,2,3]:
    offset[0]=j+each
    offset[1]=k+each
    print(offset)
    off.append(offset)
print(off)

我正在将数组附加到列表中。 我的预期输出是:

array('i', [2, 11])
array('i', [3, 12])
array('i', [4, 13])
[array('i', [2, 11]), array('i', [2, 12]), array('i', [4, 13])]

但是,我得到的输出为:

array('i', [2, 11])
array('i', [3, 12])
array('i', [4, 13])
[array('i', [4, 13]), array('i', [4, 13]), array('i', [4, 13])]

谁能帮我解决一下吗?

最佳答案

我认为j = 1,并且k = 10

并使用您的代码,如下所示:

from array import array

j,k = 1,10

off=[]
#offset=array('i',[0,0])
for each in [1,2,3]:
    offset=array('i',[0,0]) # move to here

    offset[0]=j+each
    offset[1]=k+each
    print(offset)
    off.append(offset)
print(off)

复制可以帮助您,请查看 How to clone or copy a list in Python?正如Cyber​​建议您的那样

from array import array
from copy import copy
j,k = 1,10

off=[]
offset_base=array('i',[0,0])
for each in [1,2,3]:
    offset=copy(offset_base)

    offset[0]=j+each
    offset[1]=k+each
    print(offset)
    off.append(offset)
print(off)

关于 python : Appending Integer array in list while iterating,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28215066/

相关文章:

python - 使用 "ptvsd"运行远程调试时出错

python - 如何在 Django 管理中显示 auto_now_add 字段?

arrays - 压缩给定的数组问题

python - 在 python 中使用 k 均值聚类提取质心?

python - 最有效的方法——测试 2 个字符串的 Python 字谜

c++ - 二进制搜索树递归插入导致堆栈溢出,迭代插入不起作用

python - 我无法在 heroku 上部署我的 flask 应用程序

python - 使用 pymongo 在 mongodb 中按 ObjectId 搜索

javascript - 如何使用自定义函数操作数组

c++ - 是否有可能在 C++ 中获得索引迭代器?