合并多个列表与交集并添加项目

时间:2015-11-22 15:27:19

标签: python list python-2.7

我有列表清单:

[[2, 15.0], [3, 15.0], [1, 20.0], [3, 18.0], [1, 50.0, u'pass'], [2, 10.0, u'fail'], [3, 30.0, u'pass']]

我想将这个列表合并在一起,它们具有相同的第一个元素

示例解决方案就像这样

[[1, 50.0, u'pass',20.0], [2, 10.0, u'fail',15,0], [3, 30.0, u'pass',15.0,18.0]]

这甚至可能吗? 如果可能的话,你能给我一些想法吗或者它应该如何?

3 个答案:

答案 0 :(得分:2)

您可以使用itertools.groupbyitertools.chain

的组合来完成此操作
import itertools
from operator import itemgetter


def combine_and_flatten(original, key=0):
    # Key is the index of the field to merge the lists by.
    for _, groups in itertools.groupby(sorted(original, key=itemgetter(key), itemgetter(key)):
        yield itertools.chain(*b)

答案 1 :(得分:2)

如果订单无关紧要,可以尝试

>>> l = [[2, 15.0], [3, 15.0], [1, 20.0], [3, 18.0], [1, 50.0, u'pass'], [2, 10.0, u'fail'], [3, 30.0, u'pass']]
>>> temp = {}
>>> for i in l:
...      if i[0] in temp:
...            temp[i[0]].extend(i[1:])
...      else:
...            temp[i[0]] = i[1:]
... 
>>> temp
{1: [20.0, 50.0, u'pass'], 2: [15.0, 10.0, u'fail'], 3: [15.0, 18.0, 30.0, u'pass']}
>>> new_l = [[i]+temp[i] for i in temp]
>>> new_l
[[1, 20.0, 50.0, u'pass'], [2, 15.0, 10.0, u'fail'], [3, 15.0, 18.0, 30.0, u'pass']]

在这里,您可以创建一个字典并将数字作为键。之后,将列表作为值添加到这些键。最后,您可以使用列表推导

获得所需的输出

代码 -

l = [[2, 15.0], [3, 15.0], [1, 20.0], [3, 18.0], [1, 50.0, u'pass'], [2, 10.0, u'fail'], [3, 30.0, u'pass']]
temp = {}
for i in l:
    if i[0] in temp:
          temp[i[0]].extend(i[1:])
    else:
          temp[i[0]] = i[1:]
new_l = [[i]+temp[i] for i in temp]

答案 2 :(得分:1)

让这个工作,地图/字典将发挥作用

a = [[2, 15.0],
    [3, 15.0],
    [1, 20.0],
    [3, 18.0],
    [1, 50.0, u'pass'],
    [2, 10.0, u'fail'],
    [3, 30.0, u'pass']
]

b = {x: [] for x,*y in a}

print('initial empty map : ',b)
print()

for x,*y in a:
    for z in y:
        if z not in b[x]:
            b[x].append(z)

print('filled up map: ', b)
print()

# now creating a combined list

final_list = [[x] + y for x,y in b.items()]

print('required list: ', final_list)

您可以在on repl.it

尝试解决方案
  

输出中

required list:  [[1, 20.0, 50.0, 'pass'], [2, 15.0, 10.0, 'fail'], [3, 15.0, 18.0, 30.0, 'pass']]