【问题标题】:Generate all possible unique samples with n-elements from生成所有可能的具有 n 元素的唯一样本
【发布时间】:2020-07-25 02:56:35
【问题描述】:

是否有任何简单的方法可以从任何给定的样本帧生成所有可能的唯一样本,例如。我有一个包含 5 个元素成员 = ['P', 'V', 'S', 'T', 'A'] 的列表,并且想绘制所有可能的 2 个元素组合,不考虑顺序,即“PV”是相当于'VP'。所以从列表 ['P', 'V', 'S', 'T', 'A'] 中,我应该得到 10、2 个元素样本。

我创建了一些可以解决问题的东西,但我想知道是否有一些可用的方法或函数可以做到这一点,并且可以简单地提供样本框架、样本大小并创建所有可能的组合。

members = list('PVSTA')
ms = []

   for i in members:
       for j in members:
           if i != j and i+j not in ms and j+i not in ms:
               ms.append(i+j)
           else:
               continue
print(ms)
['PV', 'PS', 'PT', 'PA', 'VS', 'VT', 'VA', 'ST', 'SA', 'TA']

【问题讨论】:

    标签: python pandas scipy statistics


    【解决方案1】:

    您可以使用itertools.combinations(iterable, r),它返回来自输入迭代的元素的长度子序列r。因此,在您的情况下,当可迭代对象为 ['P', 'V', 'S', 'T', 'A']r=2 时,它将返回 5C2 = 10 组合。

    用途:

    from itertools import combinations
    
    ms = ["".join(c) for c in combinations(list("PVSTA"), r=2)]
    print(ms)
    

    输出:

    ['PV', 'PS', 'PT', 'PA', 'VS', 'VT', 'VA', 'ST', 'SA', 'TA']
    

    【讨论】:

      【解决方案2】:

      你要做的就是所谓的组合,你可以使用python中的itertools库来做到这一点。

      from itertools import combinations
      
      members = list('PVSTA') 
      comb_2 = combinations(members, 2) 
      result = ["".join(c) for c in comb_2] 
      print(result)
      

      【讨论】:

        【解决方案3】:

        其他人已经发布了 itertools.combinations 路线(最好的方法),但是对于任何有兴趣的人来说,这里是手动方法:

        members = list('PVSTA')
        ms = []
        for i in range(len(members)-1):
          for j in range(i+1, len(members)):
            ms.append(members[i] + members[j]
        print(ms) # ['PV', 'PS', 'PT', 'PA', 'VS', 'VT', 'VA', 'ST', 'SA', 'TA']
        
        

        【讨论】:

          猜你喜欢
          • 2023-03-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-08-24
          • 1970-01-01
          • 2018-05-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多