【发布时间】:2017-10-30 19:54:15
【问题描述】:
我有两个列表 cluster0Y 和 clusterY 由 1 和 0 组成。例如。
cluster0Y = [0,1,0,0,1]
cluster1Y = [0,0,0,1]
我想从值为 1 的列表 cluster0Y 和 cluster1Y 中随机抽取 1 个元素。然后我想打印它所属的列表并打印索引。为此,我编写了以下代码:
from random import randrange
cluster0Y = [0,1,0,1]
cluster1Y = [0,1,0,1]
while True:
random_index = randrange(0,len(cluster0Y+cluster1Y))
print(str(random_index))
if random_index > len(cluster0Y):
random_index = random_index - len(cluster0Y)
if cluster1Y[random_index]==1:
print('cluster 1 ' + str(random_index))
break
else:
if cluster0Y[random_index]==1:
print('cluster 0 ' + str(random_index))
break
print(str(random_index))
但是,此代码有时会打印出列表中不是 1 的值。为什么会这样?
【问题讨论】:
-
您想从这两个列表中取样还是只从其中一个列表中取样?
-
@yklsga 从两个列表中随机抽取 1 个元素(即,如果每个列表具有相同数量的元素,则从任一列表中抽取相同的概率。)