Python - shuffle only some elements of a list

后端 未结 8 1519
礼貌的吻别
礼貌的吻别 2020-12-06 16:52

I\'m trying to shuffle only elements of a list on 3rd till last position so the 1st two will always stay in place e.g.

list = [\'a?\',\'b\',\'c\',\'d\',\'e\'         


        
8条回答
  •  情歌与酒
    2020-12-06 17:46

    l[2:] constructs a new list, and random.shuffle tries to change the list "in-place," which has no effect on l itself.

    You could use random.sample for this:

    l[2:] = random.sample(l[2:], len(l)-2)
    

提交回复
热议问题