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))
]
# 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)
如果顺序很重要,请使用
OrderedDict
并收集每个键的值:如果不是,使用
defaultdict
,您将获得稍微好一点的性能:另一个选项是使用
itertools.groupby
:这是另一种方法,尽管我不推荐。很好 我想是为了学习。你知道吗
相关问题 更多 >
编程相关推荐