[英]group the sublist seperatly inside the list based on condition in python
[英]adding items into sublist of list based on condition in python
我有2个如下的列表
list1=[['a',2,3],['b',4,5],['c',6,7]]
list2=[['a',5],['b',3],['c',8]]
我想根据子列表的条件将这2个列表作为1个列表加入。 如果列表1中子列表的第一个元素等于列表2中子列表的第一个元素,则列表2中子列表的第二个元素应添加到列表1中
结果应该是
list1=[['a',2,3,5],['b',4,5,3],['c',6,7,8]]
我可以为单个列表项执行以下操作
list1=['a',2,3]
list3=['a',5]
if list1[0]==list3[0]:
list1.extend(list3[1:])
else:
list1
print list1
帮我做上面提到的子列表一样。我无法申请2的循环。
帮我
这是您的初始数据:
>>> list1=[['a',2,3],['b',4,5],['c',6,7]]
>>> list2=[['a',5],['b',3],['c',8]]
然后,我们压缩您的列表,然后使用列表理解来生成新列表:
>>> [ a+b[1:] for a,b in zip( list1, list2 ) if a[0] == b[0] ]
结果:
[['a', 2, 3, 5], ['b', 4, 5, 3], ['c', 6, 7, 8]]
只需一行代码即可:)
编辑1
谢谢,但是如果list2 = [['a',5],['c',8],['b',3]]不起作用。 帮我
>>> list1=[['a',2,3],['b',4,5],['c',6,7]]
>>> list2=[['a',5],['c',8],['b',3]] # <--- other list2
在不同的地方使用if
:
>>> [ a+ ( b[1:] if a[0] == b[0] else [] ) for a,b in zip( list1, list2 ) ]
结果:
[['a', 2, 3, 5], ['b', 4, 5], ['c', 6, 7]]
编辑2
但是list1中的第二个和第三个子列表在list2中具有值,但未按list1顺序排列。
压缩前排序。
>>> zipped_sorted_list = zip( sorted(list1), sorted(list2) )
>>> [ a+ ( b[1:] if a[0] == b[0] else [] ) for a,b in zipped_sorted_list ]
结果
[['a', 2, 3, 5], ['b', 4, 5, 3], ['c', 6, 7, 8]]
我可以建议将主列表转换为字典:
dict1 = { e[0]:e[1:] for e in list1 }
print(dict1)
#=> {'a': [2, 3], 'c': [6, 7], 'b': [4, 5]}
然后遍历list2
向dict添加元素:
for e in list2:
dict1[e[0]].extend(e[1:])
#=> {'a': [2, 3], 'c': [6, 7], 'b': [4, 5]}
如果您需要将其作为列表(待排序):
result = [ [k] + v for k, v in dict1.items() ]
print(result)
#=> [['a', 2, 3, 5], ['c', 6, 7, 8], ['b', 4, 5, 3]]
list1=[['a',2,3],['b',4,5],['c',6,7]]
list2=[['a',5],['b',3],['c',8]]
#Sort the lists by first element in each sublist
list1.sort(key=lambda x: x[0])
list2.sort(key=lambda x: x[0])
#this count is used with the next loop in order to keep track of comparison
#between list1's sublists with list2's sublists.
count = 0
for sublist in list1:
if sublist[0] == list2[count][0]: #comparison logic here
sublist.extend(list2[count][1:])
count += 1 #increment the count each loop
print (list1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.