1

我正在使用 python 2.7,我试图根据两个值在列表列表中查找重复列表。例如

list= [[a,x,y,2], [b,xx,yy,2], [c,xxx,yyy,3],[a,yx,yx,2]]

outcome [[a,xyx,yyx,2], [b,xx,yy,2], [c,xxx,yyy,3]]

所以基于值a和2,加入其他值

有什么建议么??

谢谢您最好的问候

4

2 回答 2

2

I suppose you could use a dict if order doesn't matter:

from operator import itemgetter
getter = itemgetter(0,-1)

def merge(lst1,lst2):
    return [lst1[0],lst1[1]+lst2[1],lst1[2]+lst2[2],lst1[3]]


d = {}
for sublist in lst:
    t = getter(sublist)
    if t not in d:
       d[t] = sublist
    else:
       d[t] = merge(sublist,d[t])

print d.values()

If the order matters, you could use a collections.OrderedDict instead.

于 2013-06-05T12:14:53.303 回答
1
from collections import OrderedDict
lis =  [['a','x','y',2], ['b','xx','yy',2], ['c','xxx','yyy',3],['a','yx','yx',2]]
dic = OrderedDict()
for x in lis:
   key = (x[0],x[-1])
   if key not in dic:
      dic[key] = x[1:-1]
   else:
      val =  dic[key]
      dic[key] = [a+b for a,b in zip(val,x[1:-1])]

print [[k[0]] + v + [k[1]] for k,v in dic.items()]

输出:

[['a', 'xyx', 'yyx', 2], ['b', 'xx', 'yy', 2], ['c', 'xxx', 'yyy', 3]]
于 2013-06-05T12:29:24.087 回答