Python 将相同的元素组合到一个列表中
我一直在尝试转换我的列表Python 将相同的元素组合到一个列表中,python,list,Python,List,我一直在尝试转换我的列表 alist = [[1,[1,2]],[2,[3,4,5]],[3,[1,2]],[4,[3,4,5]],[5,[5,6,7]],[6,[1,2]]] 这件事。因为这两个子列表的第二项是相同的 [[[1,3,6],[1,2]],[[2,4],[3,4,5]]] 这是我的密码 alist = [[1,[1,2]],[2,[3,4,5]],[3,[1,2]],[4,[3,4,5]],[5,[5,6,7]],[6,[1,2]]] lst=[] for i in range
alist = [[1,[1,2]],[2,[3,4,5]],[3,[1,2]],[4,[3,4,5]],[5,[5,6,7]],[6,[1,2]]]
这件事。因为这两个子列表的第二项是相同的
[[[1,3,6],[1,2]],[[2,4],[3,4,5]]]
这是我的密码
alist = [[1,[1,2]],[2,[3,4,5]],[3,[1,2]],[4,[3,4,5]],[5,[5,6,7]],[6,[1,2]]]
lst=[]
for i in range(len(alist)):
inner = []
inner1=[]
for j in range(i+1,len(alist)):
if i+1 < len(alist):
if alist[i][1] == alist[j][1]:
inner1.append(alist[i][0])
inner1.append(alist[j][0])
inner.append(inner1)
inner.append(alist[i][1])
lst.append(inner)
print(lst)
当只有两个元素是相同的,但当有三个元素时,它就不起作用了。
范例
有人能提供一个解决方案吗?您可以使用dict(一种订购的,因为您必须维护订单)将“头”按“尾”分组:
印刷品
[[[1, 3, 6], [1, 2]], [[2, 4], [3, 4, 5]], [[5], [5, 6, 7]]]
如果要省略5
(一个只有一个“head”的组),请在res=
行中添加一个条件:
res = [[heads, list(tail)] for tail, heads in c.items() if len(heads) > 1]
非常感谢:)很抱歉,如果我说的太复杂了,我真的不知道该怎么解释我的问题。@Hal:没问题;)
alist = [[1,[1,2]],[2,[3,4,5]],[3,[1,2]],[4,[3,4,5]],[5,[5,6,7]],[6,[1,2]]]
from collections import OrderedDict
c = OrderedDict()
for head, tail in alist:
c.setdefault(tuple(tail), []).append(head)
res = [[heads, list(tail)] for tail, heads in c.items()]
print res
[[[1, 3, 6], [1, 2]], [[2, 4], [3, 4, 5]], [[5], [5, 6, 7]]]
res = [[heads, list(tail)] for tail, heads in c.items() if len(heads) > 1]