我有以下代码:
import random
SEED = 448
myList = [ 'list', 'elements', 'go', 'here' ]
random.seed(SEED)
random.shuffle(myList)
print "RUN1: ", myList
random.seed(SEED)
random.shuffle(myList)
print "RUN2: ", myList
现在我期待RUN1和RUN2产生相同的结果:
RUN1: ['here', 'go', 'list', 'elements']
RUN2: ['here', 'go', 'list', 'elements']
但它反而给出了这一点。
RUN1: ['here', 'go', 'list', 'elements']
RUN2: ['elements', 'list', 'here', 'go']
如何修改我的代码以获得我期望的结果行为?
答案 0 :(得分:3)
只是把@Tim Peters'评论回答。您需要每次都重置列表,因为random.shuffle
具有破坏性:
import random
SEED = 448
original_list = ['list', 'elements', 'go', 'here']
random.seed(SEED)
my_list = original_list[:]
random.shuffle(my_list)
print "RUN1: ", my_list
random.seed(SEED)
my_list = original_list[:]
random.shuffle(my_list)
print "RUN2: ", my_list
# Output:
# RUN1: ['here', 'go', 'list', 'elements']
# RUN2: ['here', 'go', 'list', 'elements']