Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
56 views
in Technique[技术] by (71.8m points)

List on python appending always the same value


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A simplified example of your code currently to explain more fully why your results are the way they are:

all_items = []
new_item = {}
for i in range(0,5):
    new_item['a'] = i
    new_item['b'] = i

    all_items.append(new_item)
    print new_item
    print hex(id(new_item))  # print memory address of new_item

print all_items

Notice the memory address for your object is the same each time you go through your loop. This means that your object being added is the same, each time. So when you print the final list, you are printing the coordinates of the same object at every location in the loop.

Each time you go through the loop, the values are being updated - imagine you are painting over the same wall every day. The first day, it might be blue. The next day, you repaint the same wall (or object) and then it's green. The last day you paint it orange and it's orange - the same wall is always orange now. Your references to the attr object are like saying you have the same wall.

Even though you looked at the wall after painting it, the color changed. But afterwards it is a orange wall - even if you look at it 5 times.

When we make the object as a new object in each iteration, notice two things happen:

  1. the memory address changes
  2. the values persist as unique values

This is similar to painting different walls. After you finish painting the last one, each of the previous walls is still painted the color you first painted it.

You can see this in the following, where each object is created each iteration:

all_items = []
for i in range(0,5):
    new_item = {}
    new_item['a'] = i
    new_item['b'] = i

    all_items.append(new_item)
    print hex(id(new_item))


 print all_items

You can also do in a different way, such as:

all_items = []
for i in range(0,5):
    new_item = {'a': i, 'b': i}
    all_items.append(new_item)
    print hex(id(new_item))    
print all_items

or even in one step:

all_items = []
for i in range(0,5):
    all_items.append({'a': i, 'b': i})

print all_items

Either of the following will therefore work:

attr = {}
attr['height'] = height 
attr['weight'] = weight

men.append(attr)

or:

men.append({'height': height, 'weight': weight})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...