【问题标题】:Python program to get subsets of a list in an orderPython程序按顺序获取列表的子集
【发布时间】:2020-01-12 21:50:34
【问题描述】:
def combinations(s, r):   
    # combinations('ABCD', 2) --> AB AC AD BC BD CD  
    pool = tuple(s)  
    n = len(pool)

    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)

def findsubsets(s, n):

    for i in range(0,size):
        return list(map(set, combinations(s, n)))

size = int(input("list size:"))      
s = list(input("enter list:"))   
for x in range(0,size):   
    print("list:",s)     
n = 2

我有一个 Python 程序来获取这样的子集。当我输入输入 {A,B,C,D} 我有正确的输出但输出顺序不正确。输入是这样的:

**list size:4    
enter list:abcd    
list: ['a', 'b', 'c', 'd']      
list: ['a', 'b', 'c', 'd']       
list: ['a', 'b', 'c', 'd']    
list: ['a', 'b', 'c', 'd']  
The output is:       
[{'b', 'a'}, {'c', 'a'}, {'d', 'a'}, {'c', 'b'}, {'d', 'b'}, {'d', 'c'}]     
I need to have output like this:       
[{'a', 'b'}, {'a', 'c'}, {'a', 'd'}, {'b', 'c'}, {'b', 'd'}, {'c', 'd'}]       
Can you help me?** 

【问题讨论】:

  • 你正在生成集合,集合是无序的。
  • 集合没有定义的顺序。只需在findsubsets 中省略将它们转换为set。事实上,这个功能没有多大意义。只需使用 combinations 即可。

标签: python mapping subset combinations


【解决方案1】:

cmets 中提到的问题是您使用的是sets,因此它们是无序的数据集合,如果您想保持顺序,可以执行以下操作:

import itertools

iterable = ['a', 'b', 'c', 'd']
output = list(itertools.combinations(iterable, 2))
print(output)

>>> [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]

【讨论】:

  • 谢谢,但我需要知道的是,如果没有像“import itertools”这样的第三方库,我怎么能做到这一点?
  • @KubilayOzturk itertools 不是第 3 方库,它是 python 语言的一部分。如果你的意思是你必须手动实现算法是另一回事。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-16
  • 1970-01-01
  • 2022-11-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多