繁体   English   中英

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

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

我在python中有问题。 我需要得到两个列表与子列表之间的差异,但是我只需要比较每个子列表的第一个元素。

例:

输入:

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

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

输出:

dif_l=[[5,1]]

总结问题,我必须从y列表中减去x列表(dif_l = yx),但仅检查每个子列表中的第一个元素。

可以使用列表理解:

    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)

将dicts作为中间步骤,将第一个值用作键。 仅返回在其他字典中找不到的那些键。

解决方案如下所示。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM