如何从python列表中随机选择一对相邻元素

时间:2018-10-27 03:42:40

标签: python python-2.7 random element

从列表中随机选择两个相邻元素的最佳方法是什么?

例如,对于给定列表M=[2,0,8,6,4,0,1,2,4,6,5,6,5,89,12,23] 假设我想选择(2,0),(6,5),(89,12),(5,89),(0,8)等元素。 这是我尝试过的代码:

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):
  D.append((random.sample(M,2)))

但是它不能给出正确的配对

4 个答案:

答案 0 :(得分:3)

使用列表的长度作为随机整数的限制,然后将其用作列表的索引,并选择下一项。

>>> a =[2,0,8,6,4,0,1,2,4,6,5,6,5,89,12,23]
>>> n_pairs = 6
>>> for _ in range(n_pairs):
...     i = random.randrange(len(a)-1)
...     print(a[i], a[i+1])

6 5
89 12
5 89
2 4
5 6
12 23

>>> 

无重复:

>>> a =[2,0,8,6,4,0,1,2,4,6,5,6,5,89,12,23]
>>> n_pairs = 6
>>> if n_pairs > len(a)//2:
    raise ValueError

>>> indices = random.sample(range(len(a)), n_pairs)
>>> result = [(a[i], a[i+1]) for i in indices]
>>> result
[(2, 0), (0, 8), (6, 5), (6, 5), (5, 89), (89, 12)]

答案 1 :(得分:2)

因此,请尝试以下操作:

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):
    idx = random.randint(0, len(M) - 2)
    D.append((M[idx], M[idx+1]))

答案 2 :(得分:0)

如果您的M很小,并且相邻对必须严格按照与M相同的顺序排列,请首先形成值对列表,然后从该列表中选择一个:

In [1]: M=[2,0,8,6,4,0,1,2,4,6,5,6,5,89,12,23]

In [2]: N = [(i, j) for i, j in zip(M[:-1], M[1:])]

In [3]: N
Out[3]:
[(2, 0),
 (0, 8),
 (8, 6),
 (6, 4),
 (4, 0),
 (0, 1),
 (1, 2),
 (2, 4),
 (4, 6),
 (6, 5),
 (5, 6),
 (6, 5),
 (5, 89),
 (89, 12),
 (12, 23)]

In [4]: import random

In [5]: random.choice(N)
Out[5]: (2, 4)

如果您希望列表按随机顺序排列并需要6对:

In [3]: random.shuffle(N)

In [4]: N[:6]
Out[4]:
[(89, 12),
 (0, 8),
 (6, 4),
 (2, 4),
 (2, 0),
 (6, 5)]

答案 3 :(得分:-1)

This appears to give the proper results. I did edit an above answer to get the proper results.

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):
    try:

        idx = random.randint(0, len(M))
        D.append((M[idx], M[idx + 1]))
        print(D)
    except:
        print('Error')