再次部分子集 - 运行到生成器对象而不是结果

时间:2014-07-09 13:39:56

标签: python python-2.7

感谢links to itertools jonrsharpe回复我的previous attempt,我有一个新的策略,即调整这些功能以符合我的要求(因此"假&#34 ;以及更长的计数器名称等)。不幸的是,我现在得到了(在Spyder和我需要提交的基于网络的提交格式中)这个结果:

[<generator object combinations_of_options>]

而不是实际值。我不知所措。如何取回实际结果而不是指向结果的指针?

def from_list(some_list):
'''turns an interable into individual elements'''
    for dummy in some_list:
        for element in dummy:
            yield element

def combinations_of_options(options, length):
    ''' yields all combinations of option in specific length
    '''
    pool = tuple(options)
    pool_len = len(pool)
    if length > pool_len:
        return
    indices = range(length)
    yield tuple(pool[index] for index in indices)
    while True:
        for index in reversed(range(length)):
            if indices[index] != index + pool_len - length:
                break
        else:
            return
        indices[index] += 1
        for dummy_index in range(index+1, length):
            indices[dummy_index] = indices[dummy_index-1] + 1
        yield tuple(pool[index] for index in indices)

def gen_proper_subsets(outcomes):
    outcomes = list(outcomes)
    max_len = len(outcomes)
    values = [combinations_of_options(outcomes, max_len) for dummy in range(max_len+1)]
    print values
    return from_list(values)

输入/输出所需: 在(4,2,2) out(4,2,2),(4,2),(2,2),(4,),(2,),()

<2,4>(2,4,2) out(2,4,2),(2,4),(4,2),(2,2),(4,),(2,),()

1 个答案:

答案 0 :(得分:1)

调用combinations_of_outcomes()函数确实会返回一个生成器,您必须迭代它才能提取值。也许不是

values = [combinations_of_options(outcomes, max_len) for dummy in range(max_len+1)]
你可以尝试

values = [list(combinations_of_options(outcomes, max_len)) for dummy in range(max_len+1)]

看起来目前max_len的值为零,因此您只在结果中看到一个生成器。完成此更改后,您将看到包含列表的一个列表元素。