在Python中追加会在计算值之间添加额外的意外元素

时间:2013-04-26 20:41:52

标签: python list loops append

我正在生成一些数字,每次生成一个数字时我想将它存储在列表中。

代码:

for m in plaintexts:
    H = V = []

    for k in xrange(0, 256):
        di = m[i_temp1 : i_temp2]
        entry = int(sBox[int(di, 16) ^ k])
        print entry
        V.append(entry)
        print V
        H.append(bin(entry).count("1"))
    tempV.append(V)
    tempH.append(H)

不幸的是,我得到的是完全不同的:

89
[89]
250
[89, 4, 250]
240
[89, 4, 250, 6, 240]
71
[89, 4, 250, 6, 240, 4, 71]
130
[89, 4, 250, 6, 240, 4, 71, 4, 130]
202
[89, 4, 250, 6, 240, 4, 71, 4, 130, 2, 202]
125
[89, 4, 250, 6, 240, 4, 71, 4, 130, 2, 202, 4, 125]

我正在计算我计算的值,但是在每个计算值之间总是添加一个随机数,这些随机值总是在2-8之间。

为什么?

2 个答案:

答案 0 :(得分:3)

HV相同的列表。为每个创建单独的列表:

H, V = [], []

H = V = []仅创建一个列表,然后将其分配给HV

>>> H = V = []
>>> H is V
True
>>> H.append(42)
>>> V
[42]
>>> H, V = [], []
>>> H is V
False
>>> H.append(42)
>>> V
[]

答案 1 :(得分:0)

>>> a=b=[]
>>> a.append('hello b')
>>> a,b
(['hello b'], ['hello b'])
>>> a,b=[],[]
>>> a.append('sorry b')
>>> a,b
(['sorry b'], [])