【问题标题】:list of lists rather than list of tuples - python列表列表而不是元组列表 - python
【发布时间】:2013-06-13 22:52:10
【问题描述】:

我正在开发一个程序,该程序将提供值列表的所有组合而无需重复。只要 [10, 9, 8] 和 [8, 9, 10] 都不可能,结果如何排序并不重要。到目前为止,我有一段代码可以满足我的要求,但我希望结果是列表格式而不是元组。它使用 sage 库中的 unordered_tuples 函数,但所做的只是返回一个列表列表,如下所示:

>from sage.all import unordered_tuples
>tuples = unordered_tuples([10,9,8],2) 
>print tuples
[[8, 8], [8, 9], [8, 10], [9, 9], [9, 10], [10, 10]] 

还有:

from itertools import product
def combos():
    dicti = {} 
    index = 0 
    for entry in [1,0,1,0]: 
        dicIndex = str('0')+str(index) 
        print dicIndex 
        if entry == 0: dicti[dicIndex] = [[0]] 
        else: dicti[str('0')+str(index)] = unordered_tuples([10,9,8],entry) 
        index += 1 
    lis = ['00','01','02','03'] 
    value = dicti[lis[0]] 
    print dicti 
    for index in lis[1:]: 
        value = product(value, dicti[index]) 
        if index == lis[-1]: 
            print list(value) 
            print 

输出:

[((([8], [0]), [8]), [0]), ((([8], [0]), [9]), [0]), ((([8], [0]), [10]), [0]), ((([9], [0]), [8]), [0]), ((([9], [0]), [9]), [0]), ((([9], [0]), [10]), [0]), ((([10], [0]), [8]), [0]), ((([10], [0]), [9]), [0]), ((([10], [0]), [10]), [0])] 

想要:

[[[8], [0], [8], [0]], [[8], [0], [9], [0]], [[8], [0], [10], [0]], [[9], [0], [8], [0]], [[9], [0], [9], [0]], [[9], [0], [10], [0]], [[10], [0], [8], [0]], [[10], [0], [9], [0]], [[10], [0], [10], [0]]]

【问题讨论】:

  • 输入和输出我都不懂。
  • 老实说,我也不会。我的一个同事让我问了这个问题,这正是我得到的。明天我会向她询问更多细节,以使问题更容易理解。

标签: python list tuples itertools


【解决方案1】:
output = [[[tuple[0]], [0], [tuple[1]], [0]] for tuple in unordered_tuples([10,9,8],2)]

【讨论】:

    【解决方案2】:

    我在从 PostgreSQL 数据库中提取数据时遇到了类似的问题。这是我使用的方法。

    def tupleToList(t):
        l = []
        for i in xrange(len(t)):
            l.append(list(t[i]))
            pass
        return l
        pass
    

    这适用于二维列表。在您的情况下,我正在努力将其应用于 5D 列表。

    【讨论】:

      猜你喜欢
      • 2013-09-26
      • 2014-07-04
      • 2017-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-31
      相关资源
      最近更新 更多