vendredi 26 octobre 2018

How to select randomly a pairs of adjacent elements from a python list

What is the best way to select randomly two adjacent elements from a list?

As for example, for a given list M=[2,0,8,6,4,0,1,2,4,6,5,6,5,89,12,23] Suppose I would like to select elements like (2,0),(6,5),(89,12),(5,89),(0,8) etc. Here is the code I have tried :

import random
D=[]
M=[2,0,8,6,4,0,1,2,4,6,5,6,5,89,12,23]
  for r in range(10):
  M.append((random.sample(M,2)))

But it does not give the right pairs




Aucun commentaire:

Enregistrer un commentaire