[英]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 :例如,对于给定的列表
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)))
But it does not give the right pairs但它没有给出正确的配对
Use the length of the list as a limit for a random integer then use it as an index into the list, also select the next item.使用列表的长度作为随机整数的限制,然后将其用作列表的索引,同时选择下一项。
>>> 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
>>>
Without repeats:无重复:
>>> 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)]
So, try this:所以,试试这个:
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]))
If your M is small and your adjacent pair should strictly be in the same order as M, first form the value pair list and then choose one from that list:如果您的 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)
If you want the list in a shuffled order and want 6 pairs:如果您想要以无序排列的列表并想要 6 对:
In [3]: random.shuffle(N)
In [4]: N[:6]
Out[4]:
[(89, 12),
(0, 8),
(6, 4),
(2, 4),
(2, 0),
(6, 5)]
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.