There are two lists
l1 = [1, 2.3, 1.4, 1.1]
l2 = [2.1, 0.9, 1.1, 3.2]
and I want to find the elements in the lists that have the maximum difference between the lists.
I.e.:
l1 = [1, 2.3, 1.4, 1.1] should return 0 for index 0 of the smallest number
l2 = [2.1, 0.9, 1.1, 3.2] should return 3 for index 3 of the highest number
CodePudding user response:
Try this:
l1 = [1, 2.3, 1.4, 1.1]
l2 = [2.1, 0.9, 1.1, 3.2]
def max_diff(l1, l2):
min_l1 = min(l1)
max_l1 = max(l1)
min_l2 = min(l2)
max_l2 = max(l2)
max_diff1 = max_l2 - min_l1
max_diff2 = max_l1 - min_l2
if max_diff1 > max_diff2:
return l1.index(min_l1), l2.index(max_l2), max_diff1
else:
return l1.index(max_l1), l2.index(min_l2), max_diff2
l1_index, l2_index, max_diff = max_diff(l1, l2)
print(l1_index, l2_index, max_diff) # 0 3 2.2
Note that this computes the max difference and can return either the (min(l1), max(l2)) or (max(l1), min(l2)) depending on the items in the list.
CodePudding user response:
In case there are multiple results:
l1 = [1, 2.3, 3.2, 1]
l2 = [1, 1, 1.1, 3.2]
def find_all(list1, list2):
def return_all(func, lst):
return [pos for pos, val in enumerate(lst) if val == func(lst)]
return [return_all(max, list1), return_all(min, list2)]
def output(res, order):
print(f"max position list {order[0]}: {res[order[0] - 1]}")
print(f"min position list {order[1]}: {res[order[1] - 1]}")
if max(l1) - min(l2) > max(l2) - min(l1):
results = find_all(l1, l2)
output(results, (1, 2))
elif max(l1) - min(l2) < max(l2) - min(l1):
results = find_all(l2, l1)
output(results[::-1], (2, 1))
else:
results = find_all(l1, l2)
output(results, (1, 2))
print ('And:')
results = find_all(l2, l1)
output(results[::-1], (2, 1))
output:
max position list 1: [2]
min position list 2: [0, 1]
And:
max position list 2: [3]
min position list 1: [0, 3]
CodePudding user response:
Here's a more concise approach:
l1 = [1, 2.3, 1.4, 1.1]
l2 = [2.1, 0.9, 1.1, 3.2]
for k, v in {min: ['lo', l1], max: ['hi', l2]}.items():
print(f'{v[0]}={k(range(len(v[1])), key=v[1].__getitem__)}')
Output:
lo=0
hi=3