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

2024-10-01 11:19:56 发布

您现在位置:Python中文网/ 问答频道 /正文

这和压平列表不一样。你知道吗

我有一份清单:

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]]]

我该怎么做?你知道吗


Tags: 列表v2na本例listoflists压平
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]]]

这是另一种方法,尽管我不推荐。很好 我想是为了学习。你知道吗

# 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)

相关问题 更多 >