簡體   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