【问题标题】:generate list of no repeated tuples and doesn't have both of (a,b) and (b,a) tuples, python生成没有重复元组的列表并且没有(a,b)和(b,a)元组,python
【发布时间】:2020-03-31 16:27:18
【问题描述】:

如何生成元素不重复的元组列表?另外,如果列表中有(a,b)元组,则不会在该列表中生成(b,a)。

我使用here 的以下代码,但它不提供第二个条件:

[tuple(i) for i in np.random.randint(5242, size=(500,2))]

【问题讨论】:

  • 列表有多长?那么任何随机的数字元组?
  • 列表有 500 个元组,每个数字的范围是 0 到 5242 @Dani Mesejo
  • 实际上,list 包含 500 个元组,其元素范围为 0 到 5242@Dani Mesejo

标签: python numpy random


【解决方案1】:

我不确定你是否会得到任何一种单线来干净地做到这一点。我会做类似的事情:

num_set = set()
while len(num_set) < 500:
    a, b = random.randint(0, 5242), random.randint(0, 5242)
    if (b, a) not in num_set:
        num_set.add((a, b))
num_list = list(num_set)

【讨论】:

    【解决方案2】:

    看起来您对更像一组集合而不是纯元组的东西感兴趣。如果你的对象是可排序的,你可以使用这个常见的技巧:

    included_set = set()
    included_list = list()
    input_list = np.random.randint(5242, size=(500,2))
    
    for (a, b) in input_list:
        sorted_version = tuple(sorted((a, b)))
        if sorted_version not in included_set:
            included_set.add((a, b))
            included_list.append((a, b))
    

    如果您的对象不可排序,但可散列且可比较,您可以调整上述内容以使其正常工作:

    for (a, b) in input_list:
        if (a, b) not in included_set and (b, a) not in included_set:
            included_set.add((a, b))
            included_list.append((a, b))
    

    请注意,如果要保留输入列表的顺序,只需将included_listincluded_set 分开即可。如果不是,并且您不关心元组排序(a, b),请使用:

    uniques = {tuple(sorted(tup)) for tup in input_list}
    

    【讨论】:

      【解决方案3】:

      您可以使用 python 内置库中的random.sample

      nums = random.sample(range(5242), 1000)
      res = [tuple(v) for v in zip(nums[::2], nums[1::2])]
      

      【讨论】:

      • 因为 random.sample 返回唯一元素,这段代码意味着如果 (a, b) 存在,则永远不能选择 (a, c)。因此,它在返回值中引入了偏差(这可能对 OP 很重要,也可能无关紧要)。
      • 好点。我考虑过,但由于 OP 说“其元素不重复”,我认为它符合要求。
      • 超过 500,我得到这个错误:在样本中引发 ValueError("Sample 大于 population or isnegative") ValueError: Sample large than population or isnegative
      • 因为在这条评论中没有500 存在,我假设你将 1000 更改为 > 5242。
      • 我没想到您会预测使用此代码超过 500。我只是想告诉其他人您的代码会出现非常大的错误,例如 14000。这并不意味着此代码错了!!@acushner
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-08
      • 2021-02-18
      • 1970-01-01
      相关资源
      最近更新 更多