[英]append last element of nested lists in another nested list if condition met
I have 2 list of lists:我有 2 个列表:
a = [[1,2,3], [4,5,6]]
b= [[1,8,9], [4,10,11]]
I want to add the last elements in any list of b to the end of list a if they share the first element.如果它们共享第一个元素,我想将b的任何列表中的最后一个元素添加到列表a的末尾。
for example, in my above lists, a and b share the first elements in their nested lists例如,在我上面的列表中,a 和 b 共享嵌套列表中的第一个元素
a[0][0] = b[0][0]
a[1][0] = b[1][0]
the result I want is我想要的结果是
a = [[1,2,3,9], [4,5,6,11]]
If you know that a & b lists have the same length you can do it like this:如果您知道 a & b 列表具有相同的长度,您可以这样做:
a = [[1,2,3], [4,5,6]]
b = [[1,8,9], [4,10,11]]
for x in range(len(a)):
if a[x][0] == b[x][0]:
a[x].append(b[x][-1])
print(a)
for item_a, item_b in zip(a,b):
if item_a[0] == item_b[0]:
item_a.append(item_b[-1])
Using zip to combine combine a,b by index.使用 zip 按索引组合 a、b。 List comprehension to append B[-1] if first element matches.如果第一个元素匹配,则列出对 append B[-1] 的理解。
print([A+B[-1:] if A[0]==B[0] else A for A,B in zip(a,b)])
If you don't know the size of the lists then:如果您不知道列表的大小,那么:
def main(input_list1, input_list2):
return_list = []
for combined_lists in zip(input_list1, input_list2):
list1 = combined_lists[0]
list2 = combined_lists[1]
first_idx1 = list1[0]
first_idx2 = list2[0]
if first_idx1 == first_idx2:
last_index2 = list2[len(list2)-1]
current_list = []
for elem in list1:
current_list.append(elem)
current_list.append(last_index2)
return_list.append(current_list)
return return_list
if __name__ == '__main__':
a = [[1, 2, 3], [4, 5, 6]]
b = [[1, 8, 9], [4, 10, 11]]
ret_list = main(input_list1=a, input_list2=b)
print(ret_list)
Output is: Output 是:
[[1, 2, 3, 9], [4, 5, 6, 11]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.