码迷,mamicode.com
首页 > 移动开发 > 详细

python: the difference between append and extend

时间:2017-04-25 23:39:05      阅读:440      评论:0      收藏:0      [点我收藏+]

标签:python   expec   iterable   sed   ora   cts   diff   cal   data   

Data Analysis: indoor localization using received signal strength (RSS)

An error about list operation in python: append and extend elements

We define a list A to storage objects, which the length is unknown, and list B and C to storage the final result.

The code like bellow:

# begin

   A = []

   B = []

   C = []

   for obj in range(110):

      add ten objects to A, A = [a0,a1,a2….a9]

      B.extend(A)

      C.append(A)

      del A[:]

# end

the expected result is:

B = [a0, a1, a2,a3 ……,a 1098, a1099]  // which has 1100 elements

C = [[a0, a1….a9], [a10, a11…a19]…. [a1090, a1091…a1099]] // which has 110 elements

But when I run the code, the bug appear, the real result as follow:

B = [a0, a1, a2,a3 ……,a 1098, a1099]  // which has 1100 elements

C = [[], []…. []]  // which has nothing in each list

 

Then I research the difference between append and extend through google

append : append object to the end

extend : extend list by iterable

 

Finally, I print the result in each cycle, the list B using extend looked fine, but the list C using append came wrong, it showed like bellow:

C = [[A1]]

C = [[A2],[A2]]

C = [[A3],[A3],[A3]]

…..

C = [[A109],[A109],…[A109]]

Then I make a deep copy from A to D, then append the D to the C, like bellow:

# begin

   A = []

   B = []

   C = []

   for obj in range(110):

      add ten objects to A, A = [a0,a1,a2….a9]

      B.extend(A)

      D = copy.deepcopy(A)

      C.append(D)

      del A[:]

# end

Run the code and the result came right.

So , when using extend, it will copy all elements in A to the list B, but when using append, it will only copy the address of A to list C, so, in the end, the A will be empty, which caused the result: list C has nothing.

python: the difference between append and extend

标签:python   expec   iterable   sed   ora   cts   diff   cal   data   

原文地址:http://www.cnblogs.com/yanwei93/p/6765043.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!