简体   繁体   English

带有子列表的两个列表之间的差异是每个子列表中的第一个元素

[英]The difference between the two lists with sublists by the first element in each sublist

I have a problem in python. 我在python中有问题。 I need to get differences between the two lists with sublists, but I need only comparing first element of each sublists. 我需要得到两个列表与子列表之间的差异,但是我只需要比较每个子列表的第一个元素。

Example: 例:

Input: 输入:

x=[[1,2],[2,3],[4,5]]

y=[[1,8],[5,1]]

Output: 输出:

dif_l=[[5,1]]

Summarizing the problem, I have to subtract the x list from the y list (dif_l=yx), but only check first element from each sublists. 总结问题,我必须从y列表中减去x列表(dif_l = yx),但仅检查每个子列表中的第一个元素。

Can use list comprehension: 可以使用列表理解:

    x=[[1,2],[2,3],[4,5]]

    y=[[1,8],[5,1]]

    diff_l = [l for l in y if l[0] not in [k[0] for k in x]]
    print(diff_l)

Use dicts as an intermediate step with the first values as keys. 将dicts作为中间步骤,将第一个值用作键。 Return only those keys not found in the other dict. 仅返回在其他字典中找不到的那些键。

A solution can look like this. 解决方案如下所示。

x=[[1,2],[2,3],[4,5]]

y=[[1,8],[5,1]]

def custom_sublist_subtract(left, right):
    ''' y - x should be passed as (y, x)
    '''
    dict_left = {item[0]: item for item in left}
    dict_right = {item[0]: item for item in right}
    result = [v for k, v in dict_left.items() if k not in dict_right]
    return result

custom_sublist_subtract(y, x)
#Output:
[[5, 1]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何获得两元素子列表的两个列表之间的对称差异? - How can the symmetric difference between two lists of two-element sublists be obtained? 将算术函数应用于子列表的元素,其中每个子列表的第一个元素相同 - Applying arithmetic functions to elements of sublists where the first element of each sublist is the same Python:如何在不知道子列表数目的情况下遍历每个子列表的第一个元素? - Python: how do i iterate over the first element of each sublist without knowing the number of sublists? 基于子列表中的第一个元素的列表的集群列表 - cluster list of lists based on the first element in the sublist 有效地查找两个列表之间的元素差异 - Finding an element difference between two lists efficiently 计算两个列表的每个元素之间的差异 - Calulate the differences between each element of two lists 返回两个列表列表中第一个不同的元素并停止比较 - return the first element with a difference from two lists of lists and stop to compare 如何将列表列表组合成字典,其中第一个子列表映射到所有后续子列表中的相应值? - How to combine a list of lists into a dictionary where the first sublist is mapped to corresponding values in all subsequent sublists? 循环打印两个列表,以获得两列在每个列表的每个元素的第一个字母之间具有固定(自定义集)空间 - Loop print through two lists to get two columns with fixed(custom set) space between the first letter of each element of each list 将列表划分为子列表,使得子列表中任意 2 个元素之间的差异不应超过 k - Divide a list into sublists such that difference between any 2 elements in a sublist should not exceed k
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM