【问题标题】:Sample random element from two lists where value = 1从两个值 = 1 的列表中抽样随机元素
【发布时间】:2017-10-30 19:54:15
【问题描述】:

我有两个列表 cluster0YclusterY 由 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 个元素(即,如果每个列表具有相同数量的元素,则从任一列表中抽取相同的概率。)

标签: python list


【解决方案1】:

你肯定挑选值不是 1,但不打印它们。您正在打印指向非 1 值的随机索引。

你也可以重新思考你的逻辑,让它看起来更像

extract the indices of 1 values in list0
extract the indices of 1 values in list1
pick a random option from the extracted indices

类似的东西:

allOnes0 = [(ind, 0) for ind, v in enumerate(cluster0Y) if v == 1]
allOnes1 = [(ind, 1) for ind, v in enumerate(cluster1Y) if v == 1]
(index, clusterId) = random.choice(allOnes0 + allOnes1)

clusterId 告诉你随机 1 是来自集群 0 还是 1,index 告诉你 1 在集群中的位置。

这更简单,更不容易出错。

【讨论】:

    【解决方案2】:

    在这里按预期工作,但您必须修复一个错误:

    if random_index > len(cluster0Y):
    

    .. 如果 random_index 的大小正好是 len(clu​​ster0Y),这将在稍后从 cluster0Y 读取失败。

    if random_index >= len(cluster0Y):
    

    【讨论】:

      【解决方案3】:

      我认为你的代码对于你想要实现的目标来说太复杂了。

      您可以使用[idx for idx, val in enumerate(cluster) if val != 0] 之类的东西来查找非零元素的索引并从那里开始。

      至于为什么有时会打印0,我认为@MatsLindh找到了原因。

      【讨论】:

        【解决方案4】:

        我稍微修改了您的代码。我把它改成了>=,因为根据你的代码random_index = 4,它不满足条件random_index > len(cluster0Y),你会得到一个列表超出范围的错误

        from random import randrange
        cluster0Y = [0,1,0,1]
        cluster1Y = [0,1,0,1]
        while True:
                random_index = randrange(0,len(cluster0Y+cluster1Y))
                if random_index >= len(cluster0Y):
                    random_index = random_index - len(cluster0Y)
                if cluster1Y[random_index]==1:
                    print('cluster 1 : ',random_index)
                    break
                if cluster0Y[random_index]==1:
                    print('cluster 0 : ',random_index)
                    break
                print('random index = ',random_index)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-12-07
          • 1970-01-01
          • 2013-04-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多