【问题标题】:Python_grouping multidimensional listPython_grouping 多维列表
【发布时间】:2016-03-15 10:22:25
【问题描述】:

我有一个示例多维列表:

    example_list=[
        ["a","b","c", 2,4,5,7],
        ["e","f","g",0,0,1,5],
        ["e","f","g", 1,4,5,7],
        ["a","b","c", 3,2,5,7]
    ]

如何将它们分成这样的组:

out_list=[
         [["a","b","c", 2,4,5,7],
           ["a","b","c",3,2,5,7]
         ],
         [["e","f","g", 0,0,1,5],
          ["e","f","g", 1,4,5,7]
         ]
 ]

我试过这个:

example_list=[["a","b","c", 2,4,5,7],["e","f","g", 0,0,1,5],["e","f","g",1,4,5,7],["a","b","c", 3,2,5,7]]
unique=[]
index=0
for i in range(len(example_list)):
    newlist=[]
    if example_list[i][:3]==example_list[index][:3]:
        newlist.append(example_list[i])
    index=index+1
    unique.append(newlist)            
print unique

我的结果是这样的:

[[['a', 'b', 'c', 2, 4, 5, 7]], [['e', 'f', 'g',0, 0, 1, 5] ], [['e', 'f', 'g', 1, 4, 5, 7]], [['a', 'b', 'c', 3, 2, 5,7]]]

我想不通。

【问题讨论】:

  • 分组是否取决于前三个元素?

标签: python multidimensional-array python-2.5


【解决方案1】:

如果分组由每个列表中的前三个元素决定,则以下代码将满足您的要求:

from collections import defaultdict

example_list=[["a","b","c", 2,4,5,7],["e","f","g",0,0,1,5],["e","f","g", 1,4,5,7],["a","b","c", 3,2,5,7]]
d = defaultdict(list)
for l in example_list:
    d[tuple(l[:3])].append(l)

print d.values() # [[['a', 'b', 'c', 2, 4, 5, 7], ['a', 'b', 'c', 3, 2, 5, 7]], ...]

这将使用defaultdict 生成一个字典,其中键是前三个元素,值是以这些元素开头的列表列表。

【讨论】:

    【解决方案2】:

    首先简单地使用sorted()对列表进行排序,提供lambda函数作为键。

    >>> a = sorted(example_list, key=lambda x:x[:3])
    [['a', 'b', 'c', 2, 4, 5, 7], ['a', 'b', 'c', 3, 2, 5, 7], ['e', 'f', 'g', 0, 0, 1, 5], ['e', 'f', 'g', 1, 4, 5, 7]]
    

    然后在排序列表上使用itertools.groupby()

    >>> [list(v) for k, v in groupby(a, lambda x:x[:3])]
    [
        [['a', 'b', 'c', 2, 4, 5, 7], ['a', 'b', 'c', 3, 2, 5, 7]], 
        [['e', 'f', 'g', 0, 0, 1, 5], ['e', 'f', 'g', 1, 4, 5, 7]]
    ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 2017-02-19
      • 2018-06-22
      相关资源
      最近更新 更多