I have a problem in 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.
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. 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]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.