Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

list - why doesn't append in python work properly?

def get_next_state_for_x(list, next_state):
    final = []
    state = list
    for g in range (len(next_state)):
        temp = state[g]
        state[g] = next_state[g]
        print(state)
        final.append(state)
        state[g] = int(temp)
    print(final)
get_next_state_for_x([0, 0, 0, 0], [1, 1, 1, 1])

so while i compile this code i get the output:

[1, 0, 0, 0]
[0, 1, 0, 0]
[0, 0, 1, 0]
[0, 0, 0, 1]
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

instead of (for the last line)

[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]

why does final.append(state) add wrong list to the result ?

question from:https://stackoverflow.com/questions/65893446/why-doesnt-append-in-python-work-properly

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

1 Answer

0 votes
by (71.8m points)

You're linking the list, so it changes everytime. You have to copy it

Correct to:

final.append(state.copy())

So:

def get_next_state_for_x(list, next_state):
    final = []
    state = list
    for g in range (len(next_state)):
        temp = state[g]
        state[g] = next_state[g]
        print(state)
        final.append(state.copy())
        state[g] = int(temp)
    print(final)
get_next_state_for_x([0, 0, 0, 0], [1, 1, 1, 1])

Output:

[1, 0, 0, 0]
[0, 1, 0, 0]
[0, 0, 1, 0]
[0, 0, 0, 1]
[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...