Python函数正在创建一个额外的元组

时间:2017-03-23 06:42:01

标签: python python-2.7 loops tuples itertools

我的原始功能基于this postthis postthis post。但它不起作用。我得到的主要问题是即使我在例二中放置元组(c),我仍然会得到一个列表。

我有两个例子,一个是嵌套元组(应该是这样的),一个是列表中嵌套元组,这样你就可以很容易地看到额外的外壳,因为嵌套元组的括号太多了。

def example_one():
    list_one = ((1, 2), (3, 4), (5, 6), (7, 8), (9, 10))
    list_two = []
    print "List One: " + str(list_one)      
    for i in range(0, 5):
        c_tuple = tuple(c for c in itertools.combinations(list_one[:i], i))
        list_two.append(c_tuple)
    list_two = tuple(list_two)
    print "List Two: " + str(list_two)

输出:

List One: ((1, 2), (3, 4), (5, 6), (7, 8), (9, 10))
List Two: (((),), (((1, 2),),), (((1, 2), (3, 4)),), (((1, 2), (3, 4), (5, 6)),), (((1, 2), (3, 4), (5, 6), (7, 8)),))

def example_two():
    list_one = ((1, 2), (3, 4), (5, 6), (7, 8), (9, 10))
    list_two = []
    print "List One: " + str(list_one)      
    for i in range(0, 5):
       c_tuple = [tuple(c) for c in itertools.combinations(list_one[:i], i)]
       list_two.append(c_tuple)
    list_two = tuple(list_two)
    print "List Two: " + str(list_two)

输出:

List One: ((1, 2), (3, 4), (5, 6), (7, 8), (9, 10))
List Two: ([()], [((1, 2),)], [((1, 2), (3, 4))], [((1, 2), (3, 4), (5, 6))], [((1, 2), (3, 4), (5, 6), (7, 8))])

在第二个例子中,括号代表我试图消除的例子中的元组。事实上,说实话,我不确定是否是那个元组或内部元组。无论哪个都被不必要地添加,我猜。

期望的输出:

List One: ((1, 2), (3, 4), (5, 6), (7, 8), (9, 10))
List Two: ((()), ((1, 2)), ((1, 2), (3, 4)), ((1, 2), (3, 4), (5, 6)), ((1, 2), (3, 4), (5, 6), (7, 8)))

3 个答案:

答案 0 :(得分:1)

就像你提到的那样,你可以避免做[tuple(c) for c in iterable]而只是做以下事情。 (还简化/缩小了很多东西)

>>> list_one = ((1, 2), (3, 4), (5, 6), (7, 8), (9, 10))
>>> list_two = []
>>> print "List One: ", list_one
List One:  ((1, 2), (3, 4), (5, 6), (7, 8), (9, 10))
>>> list_two = tuple(
...     c for i in range(0, 5)
...     for c in itertools.combinations(list_one[:i], i)
... )
>>> print "List Two: ", list_two
List Two:  ((), ((1, 2),), ((1, 2), (3, 4)), ((1, 2), (3, 4), (5, 6)), ((1, 2), (3, 4), (5, 6), (7, 8)))

答案 1 :(得分:0)

在第二个示例中,您将嵌套元组添加到列表中,将这些列表附加到一个大列表中,最后将该大列表转换为元组。 这就是你在元组中获取列表的原因

创建列表的行是

c_tuple = [tuple(c) for c in itertools.combinations(list_one[:i], i)]

如果你有方括号,它将只返回一个列表

答案 2 :(得分:0)

在将list_two添加到c_tuple时,你必须使用extend而不是append

要清楚了解两者之间的差异,请查看this

import itertools

def example_two():
    list_one = ((1, 2), (3, 4), (5, 6), (7, 8), (9, 10))
    list_two = []
    print "List One: " + str(list_one)      
    for i in range(0, 5):
       c_tuple = [tuple(c) for c in itertools.combinations(list_one[:i], i)]
       list_two.extend(c_tuple) #here instead of append use extend!
    list_two = tuple(list_two)
    print "List Two: " + str(list_two)

输出:

List One: ((1, 2), (3, 4), (5, 6), (7, 8), (9, 10))
List Two: ((), ((1, 2),), ((1, 2), (3, 4)), ((1, 2), (3, 4), (5, 6)), ((1, 2), (3, 4), (5, 6), (7, 8)))

希望它有所帮助!