我有一个这样的列表列表
list = [[1, 2], [1, 3], [4, 5]]
如您所见,前两个子列表的第一个元素被重复
所以我希望我的输出也是:
list = [[1, 2, 3], [4, 5]]
谢谢
我有一个解决方案,它首先使用第一个值构建一个 dict,然后从中创建一个列表,但顺序可能不同(即[4, 5]
可能在 before [1, 2, 3]
):
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> map(lambda x: d[x[0]].append(x[1]), l)
[None, None, None]
>>> d
defaultdict(<type 'list'>, {1: [2, 3], 4: [5]})
>>> [[key] + list(val) for key, val in d.iteritems()]
[[1, 2, 3], [4, 5]]
以下代码应该可以解决您的问题:
def merge_subs(lst_of_lsts):
res = []
for row in lst_of_lsts:
for i, resrow in enumerate(res):
if row[0]==resrow[0]:
res[i] += row[1:]
break
else:
res.append(row)
return res
请注意,else
属于内部for
的,如果循环在没有中断的情况下退出,则执行。
虽然可以说是不可读的:
# Note the _ after the list, otherwise you are redefining the list type in your scope
list_ = [[1, 2], [1, 3], [4, 5]]
from itertools import groupby
grouper = lambda l: [[k] + sum((v[1::] for v in vs), []) for k, vs in groupby(l, lambda x: x[0])]
print grouper(list_)
一个更易读的变体:
from collections import defaultdict
groups = defaultdict(list)
for vs in list_:
group[vs[0]] += vs[1:]
print group.items()
请注意,这些解决了您的问题的更通用形式,而不是[[1, 2], [1, 3], [4, 5]]
您也可以有这样的东西:[[1, 2, 3], [1, 4, 5], [2, 4, 5, 6], [3]]
关于的解释_
。这就是您不想覆盖的原因list
:
spam = list()
print spam
# returns []
list = spam
print list
# returns []
spam = list()
# TypeError: 'list' object is not callable
正如你在上面看到的,通过设置list = spam
我们打破了list()
.
你可以使用 python 集合,因为你可以很容易地计算交集和联合。代码会更清晰,但复杂性可能与其他解决方案相当。