如何将具有相同索引0的两个子列表合并到一个子列表中?

时间:2018-11-12 22:50:11

标签: python list

与拼合列表不同。

我有以下列表列表:

listoflists = [[853, 'na'], [854, [1, 2, 3, 4, 5]], [854, [2, 4, 6, 8]]

我希望具有相同索引0(在本例中为854)的那些子列表被合并但不被展平,例如:

listoflists_v2 = [[853, 'na'], [854, [1, 2, 3, 4, 5], [2, 4, 6, 8]]]

我该怎么做?

2 个答案:

答案 0 :(得分:2)

如果顺序很重要,请使用OrderedDict并为每个键收集值:

from collections import OrderedDict
d = OrderedDict()
for k, v in listoflists:
    d.setdefault(k, []).append(v)

listoflists_v2 = [[k, *v] for k, v in d.items()]

如果没有,请使用defaultdict,以获得更好的性能:

from collections import defaultdict
d = defaultdict(list)
for k, v in listoflists:
   d[k].append(v)

listoflists_v2 = [[k, *v] for k, v in d.items()]

另一个选择是使用itertools.groupby

from itertools import groupby
from operator import itemgetter
listoflists.sort(key=itemgetter(0)) # Do this if keys aren't consecutive.

listoflists_v2 = [
    [k, *map(itemgetter(1), g)] 
    for k, g in groupby(listoflists, key=itemgetter(0))
]

print(listoflists_v2)
[[853, 'na'], [854, [1, 2, 3, 4, 5], [2, 4, 6, 8]]]

答案 1 :(得分:0)

尽管我不建议这样做,但这是另一种解决方法。很好 我想学习。

# orginal list
listoflists = [[853, 'na'], [854, [1, 2, 3, 4, 5]], [854, [2, 4, 6, 8]]]
# new list with combined data
new_list = []

# loop through all sublists
for sub_list in listoflists:
    # check if new_list is empty to see if its data should be compared
    # with the orinal if not add sublist to new_list
    if new_list:
        # check all the lists in new_list
        for list_ in new_list:
            # if the list in new_list and one of the original lists
            # first element match, add the values of the original list
            # starting from the first elemnt to the new_list
            if sub_list[0] == list_[0]:
                list_.append(sub_list[1:])

            else:
                list_.append(sub_list)

    else:
        new_list.append(sub_list)

print(new_list)