So, I faced a problem. Suppose I have two 2D lists.
t=[[2, 'h'], [4, 'e'], [2, 'r']]
t1=[[5, 'e'], [2, 'h'], [2, 'r'], [2, 'y']]
From these two lists, if second element of the sub-list is similar, I will extract based on the maximum based on the first element. If sub-list for first and second element is similar between two 2d lists, I will extract any of them.
So, my answer is =
['=:rr', '=:hh', '2:eeeee']
Here 2 means I am getting it from B list and =: means I have that in both lists.
But the answer I want ['=:rr', '=:hh', '2:eeeee', '2:yy']
So, I can't bring that 2:yy using my code.
for x in t:
for y in t1:
if x[1]==y[1] and x[0]>y[0]:
lst.append('1:' str(x[1])*x[0])
elif x[1]==y[1] and x[0]<y[0]:
lst.append('2:' str(y[1])*y[0])
elif x[1]==y[1] and x[0]==y[0]:
lst.append("=:" str(y[1])*y[0])
thanks in advance
CodePudding user response:
Since the second elements are unique in each list, one option is to convert each list into a dictionary and analyze the intersecting keys:
dict_A = {k:v for v,k in A}
dict_B = {k:v for v,k in B}
out = []
for v in dict_A.keys() & dict_B.keys():
a, b = dict_A[v], dict_B[v]
if a > b:
out.append(f'1:{v*a}')
elif a == b:
out.append(f'=:{v*a}')
else:
out.append(f'2:{v*b}')
for v in dict_A.keys() - dict_B.keys():
out.append(f'1:{v*dict_A[v]}')
for v in dict_B.keys() - dict_A.keys():
out.append(f'2:{v*dict_B[v]}')
Output:
['=:rr', '=:hh', '2:eeeee', '2:yy']