简体   繁体   English

列表重新格式化中的Python列表

[英]Python list in list reformatting

What is the pythonic way to reorganize my following data? 重新组织以下数据的pythonic方法是什么?

I have a data 我有一个数据

data = [
        ['a','b',1], ['a','b',2], ['a','b',3],
        ['a','c',3], ['a','c',4],
        ['f','g',2], ['f','g',5], ['f','g',9]
       ]

And I want to rearrange it to following format: 我想将其重新排列为以下格式:

data = [
        ['a', 'b', 1, 2, 3], 
        ['a', 'c', 3, 4], 
        ['f', 'g', 2, 5, 9]
       ]

So basically those two first elements in each inner list is the way to differentiate different items and following number is the data. 所以基本上每个内部列表中的两个第一个元素是区分不同项目的方式,后面的数字是数据。 I only want to have one row for each item which contains all the data. 我只希望每个包含所有数据的项目都有一行。

import collections

keyed = collections.defaultdict(list) # (a,b): [1,2,3]

for k1,k2,val in data:
    keyed[(k1,k2)].append(val)

[list(keys) + vals for keys,vals in sorted(keyed.items())]

You can use a dictionary for categorizing the items based on first two items in each sub list then use a list comprehension in order to concatenate the dict's keys and values: 您可以使用字典根据每个子列表中的前两个项目对项目进行分类,然后使用列表推导来连接dict的键和值:

Note that the reason of using OrderedDict is that it will preserver the order for you. 请注意,使用OrderedDict的原因是它会为您保留订单。

>>> from collections import OrderedDict
>>> d = OrderedDict()
>>> 
>>> for i, j, k in data:
...     d.setdefault((i, j), []).append(k)
... 
>>> [[i,j] + k for (i,j), k in d.items()]
[['a', 'b', 1, 2, 3], ['a', 'c', 3, 4], ['f', 'g', 2, 5, 9]]

If you are dealing with large lists and you care about the memory optimization, you can use groupby and chain functions from itertools module that return iterator: 如果您正在处理大型列表并且关心内存优化,则可以使用返回迭代器的itertools模块中的groupbychain函数:

>>> from itertools import groupby, chain
>>> from operator import itemgetter
>>> from collections import OrderedDict

>>> [OrderedDict.fromkeys(chain.from_iterable(g)).keys() for _,g in groupby(data, key=itemgetter(0, 1))]
[['a', 'b', 1, 2, 3], ['a', 'c', 3, 4], ['f', 'g', 2, 5, 9]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM