合并python 3

时间:2017-09-22 10:50:15

标签: python python-3.x list

我有这两个清单列表:

list1= [['user1', 186, 'Feb 2017, Apr 2017', 550, 555], ['user2', 282, 'Mai 2017', 0, 3579], ['user3', 281, 'Mai 2017', 10, 60]]

list2= [['user1', 186, 'Feb 2017, Mar 2017, Mai 2017', 0, 740],['user2', 282, 'Feb 2017', 0, 1000], ['user4', 288, 'Feb 2017', 60, 10]]

我希望输出这个:

desiredlist =[['user1', 186, 'Feb 2017, Mar 2017, Mai 2017', 550, 740], ['user2', 282, 'Feb 2017', 0, 1000], ['user3', 281, 'Mai 2017', 10, 0], ['user4', 288, 'Feb 2017', 60, 10]]

为此,我有这个功能:

def mergesafirmacheta(list1,list2):
    desiredlist = []
    for id, n1, dates, n2, n3 in list1:
        counter = 0
        for list_2 in list2:
            if n1 == list_2[1]:
                desiredlist.append(list_2[:3] + [n2, list_2[4]])
            else:
                   counter += 1
                   if counter == len(list2):
                       desiredlist.append([id, n1, dates, n2, 0])
    print (desiredlist)

但这会输出:

desiredlist =[['user1', 186, 'Feb 2017, Mar 2017, Mai 2017', 550, 740], ['user2', 282, 'Feb 2017', 0, 1000], ['user3', 281, 'Mai 2017', 10, 0]]

^^ user4缺失(检查我想要的输出),我可以从我的函数中看到为什么,我尝试在我的第一个语句之后添加它:

elif list_2[1] != n1:
    desiredlist.append(list_2)

但是这不起作用,这是计算所需列表的规则:

list2[1] == list1[1](示例186 == 186)附加到我的desiredlist list2[0], list2[1], list2[2], list1[3], list2[4]时,如果list1[1]列表中的list2列表更改附加到desiredlist list1[0], list1[1], list1[2], list1[3], 0,,如果list2[1]列表中没有的list1附加到desiredlist list2[0], list2[1], list2[2], list2[3], list2[4]。这有点难以休会,但我认为更容易检查我想要的输出以及我现在实际输出的内容。

3 个答案:

答案 0 :(得分:1)

我设法通过更改格式来完成您的预期目标。我使用密钥dict将所有子列表转换为user

因为在子列表中合并dict和user的顺序更容易并不重要。

最后一步是迭代dictlist1的合并list2并执行特殊操作。据我所知,是采用前一个list1的数字并将其与list2合并。然后重新创建所需的子列表。

from itertools import chain
from collections import defaultdict

list1 = [['user1', 186, 'Feb 2017, Apr 2017', 550, 555], ['user2', 282, 'Mai 2017', 0, 3579], ['user3', 281, 'Mai 2017', 10, 60]]
list2 = [['user1', 186, 'Feb 2017, Mar 2017, Mai 2017', 0, 740],['user2', 282, 'Feb 2017', 0, 1000], ['user4', 288, 'Feb 2017', 60, 10]]

# Transform list to dict with key as 'userN'
def to_dict(lst): return {x[0]: x[1:] for x in lst} 

# Now create a dict that combined list of user1..N+1
tmp_dict = defaultdict(list)
for k, v in chain(to_dict(list1).items(), to_dict(list2).items()):
  tmp_dict[k].append(v)

desired_output = []
for k, v in tmp_dict.items():
  if len(v) == 2:
    v[1][-2] = v[0][-2] # Take the before last of list1 to remplace with before last one of list2
    desired_output.append([k] + v[1])
  else:
    desired_output.append([k] + v[0])

print(desired_output)

输出:

[['user1', 186, 'Feb 2017, Mar 2017, Mai 2017', 550, 740], ['user2', 282, 'Feb 2017', 0, 1000], ['user3', 281, 'Mai 2017', 10, 60], ['user4', 288, 'Feb 2017', 60, 10]]

修改

我似乎犯了一个错误,而您的list1必须检查list2的所有内容,在这种情况下,您应首先dict list2并申请你的具体情况。例如:

from itertools import chain

list1 = [['user1', 186, 'Feb 2017, Apr 2017', 550, 555], ['user2', 282, 'Mai 2017', 0, 3579], ['user3', 281, 'Mai 2017', 10, 60]]
list2 = [['user1', 186, 'Feb 2017, Mar 2017, Mai 2017', 0, 740],['user2', 282, 'Feb 2017', 0, 1000], ['user4', 288, 'Feb 2017', 60, 10]]

# Transform list to dict with key as 'userN'
def to_dict(lst): return {x[0]: x[1:] for x in lst} 

# First, transfrom list2 to dict
list2_dict = {}
for k, v in to_dict(list2).items():
  list2_dict[k] = v

# Then iterate on list1 to compare
desired_output = []
for k, v in to_dict(list1).items():
  if k in list2_dict: # key of list1 exists in list2
    list2_dict[k][-2] = v[-2] # replace value
    desired_output.append([k] + list2_dict[k]) # Then add list2
    list2_dict.pop(k) # And remove it from old dict
  else: # list1 does not exists in list2
    v[-1] = 0 # Set last element to zero
    desired_output.append([k] + v)

for k, v in list2_dict.items(): # Now add elements present only in list2
  desired_output.append([k] + v)

print(desired_output)

输出:

[['user1', 186, 'Feb 2017, Mar 2017, Mai 2017', 550, 740], ['user2', 282, 'Feb 2017', 0, 1000], ['user3', 281, 'Mai 2017', 10, 0], ['user4', 288, 'Feb 2017', 60, 10]]

注意:我们可以删除defaultdict,因为相同的密钥不会被添加两次。

答案 1 :(得分:1)

使用此代码:

list1= [['user1', 186, 'Feb 2017, Apr 2017', 550, 555], ['user2', 282, 'Mai 2017', 0, 3579], ['user3', 281, 'Mai 2017', 10, 60]]

list2= [['user1', 186, 'Feb 2017, Mar 2017, Mai 2017', 0, 740],['user2', 282, 'Feb 2017', 0, 1000], ['user4', 288, 'Feb 2017', 60, 10]]

final_list = []
for l1_data, l2_data in zip(list1, list2):
    if l1_data[0] == l2_data[0]:
        for index, elem in enumerate(l2_data):
            if index+1 <= len(l1_data):
                if not elem and l1_data[index]:
                    l2_data[index] = l1_data[index]                    
    else: final_list.append(l1_data)
    final_list.append(l2_data)
print final_list

Ouptut:

[['user1', 186, 'Feb 2017, Mar 2017, Mai 2017', 550, 740], ['user2', 282, 'Feb 2017', 0, 1000], ['user3', 281, 'Mai 2017', 10, 60], ['user4', 288, 'Feb 2017', 60, 10]]

答案 2 :(得分:0)

您可以遍历两个列表组合的不同第二个元素:

for n in set([item[1] for item in list1+list2]):

然后您可以通过在两个列表中查找n来决定添加到您想要的列表