列表理解以循环2个列表列表并更改数据

时间:2017-09-21 13:22:39

标签: python python-3.x list

我有这个列表理解功能:

def mergesafirmacheta(list1,list2):
    desiredlist = [list2[0][:3] + [n2, list2[0][4]] if n1 == list2[0][1]
                   else [id, n1, dates, n2, 0] for id, n1, dates, n2, n3 in list1]
    return desiredlist

我的list1和list2看起来像这样:

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

list2=[['user2', 282, 'Feb 2017, Mar 2017, Apr 2017, Mai 2017', 100, 1000],
      ['user1', 186, 'Feb 2017, Mar 2017, Apr 2017, Mai 2017', 0, 740]]

if n1 == list2[0][1]我希望遍历所有列表而不仅仅是list2中index [1]位置的第一个列表,因为现在我只能:['user2', 282, 'Feb 2017, Mar 2017, Apr 2017, Mai 2017', 100, 1000]比较282 in我的if,但是我的第二个名单中永远不会达到186。我如何循环所有这些? (可能是list2中有更多列表)。

稍后编辑:

期望的输出:

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

2 个答案:

答案 0 :(得分:0)

在乞讨时再添加一个循环并更改变量,如下所示: -

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

我希望这就是你要找的东西。

答案 1 :(得分:0)

我想这就是你要找的东西:

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

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)

只有当list1中的n1为list1的所有元素找到NO MATCH时,才想转到else条件。