【问题标题】:Is there a way of modify lists with this criterion in python?有没有办法在 python 中使用这个标准修改列表?
【发布时间】:2021-04-07 13:48:34
【问题描述】:

假设我们有一组有序的元素[a, b]

初始设置

[[1,5], [2,5], [3,5], [3,6], [4,5]]

由于我对 4 个元素的集合 感兴趣,并且我看到元素 2 和 3 具有相同的值 a,所以我想知道如何编写一个启动的程序从初始集合开始,并执行以下操作:

设置 1

[[1,5], [2,5], [3,5], [4,5]]

第二组

[[1,5], [2,5], [3,6], [4,5]]

例如,如果初始集合是:

[[1,5], [2,5], [3,5], [3,6], [4,5], [4,6]]

程序应该返回:

[[1,5], [2,5], [3,5], [4,5]]
[[1,5], [2,5], [3,5], [4,6]]
[[1,5], [2,5], [3,6], [4,5]]
[[1,5], [2,5], [3,6], [4,6]]

在 python 中有没有办法做到这一点?我曾尝试使用 combinationspermutations 模块,但在我看来,这对于任务的简单性来说太过分了。

非常感谢。

【问题讨论】:

  • 你想要集合还是列表?
  • [[1,5], [2,5], [1,4], [3,6], [4,5], [4,6]] 的输出应该是什么?
  • @inspectorG4dget,您的输入未排序
  • @joostblack:好电话。谢谢
  • @inspectorG4dget 好,假设您的意思是 Input =` [[1,4], [1,5], [2,5], [3,6], [4,5], [4,6` 在这种情况下,输出应该是:[[1,4], [1,5], [2,5], [3,6], [4,5]]List2 = [[1,4], [1,5], [2,5], [3,6], [4,6]]。它应该将输入转换为 4 个元素的列表,更改输入中重复元素 [0] 值的元素。不知道我的解释是否正确......

标签: python list sorting set combinations


【解决方案1】:

按第一个元素分组,然后得到product

import collections, itertools

lst = [[1,5], [2,5], [3,5], [3,6], [4,5]]
d = collections.defaultdict(list)
for x in lst:
    d[x[0]].append(x)

res = list(itertools.product(*d.values()))                                    
# [([1, 5], [2, 5], [3, 5], [4, 5]),
#  ([1, 5], [2, 5], [3, 6], [4, 5])]

如果列表按第一个元素排序,您也可以使用groupby,如另一个答案所示,然后获取那些的`product:

from itertools import product, groupby                                  
for x in product(*(list(g) for k, g in groupby(lst, key=lambda x: x[0]))): 
    print(x) 

【讨论】:

    【解决方案2】:
    import itertools
    import operator
    
    
    def groupify(L):  # create all the groupings
        answer = []
        for k,group in itertools.groupby(L, operator.itemgetter(0)):
            answer.append(list(group))
        return answer
    
    
    def dfs(L, answer=None):  # depth first search algorithm
        if answer is None:
            answer = []
        if not L:
            yield answer
    
        else:
            for sub in L[0]:
                yield from dfs(L[1:], answer+[sub])
    
    
    def main(L):  # do a DFS on the groupings
        for a in dfs(groupify(L)):
            print(a)
    
    

    测试:

    In [188]: main([[1,5], [2,5], [3,5], [3,6], [4,5], [4,6]])                                                                                                                                                                                                                    
    [[1, 5], [2, 5], [3, 5], [4, 5]]
    [[1, 5], [2, 5], [3, 5], [4, 6]]
    [[1, 5], [2, 5], [3, 6], [4, 5]]
    [[1, 5], [2, 5], [3, 6], [4, 6]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-01
      • 2019-03-01
      • 2020-02-12
      • 1970-01-01
      相关资源
      最近更新 更多