Home > database >  Comparing sublists of two lists in Python
Comparing sublists of two lists in Python

Time:01-03

I have two lists C22 and D22 with many sublists. I want to compare elements of each sublist and print if it meets the criterion i.e. element of each sublist of C22 is greater than element of each sublist of D22. I present the current and expected outputs.

C22 = [[[353.856161, 417.551036, 353.856161, 353.856161, 282.754301]], [[294.983702, 294.983702]]]

D22 = [[[423.81345923, 230.97804127, 419.14952534, 316.58460442, 310.81809094]], 
       [[423.81345923, 419.14952534]]]


arcond1=[]

for i in range(0,len(C22)):
    cond1=C22[i]>D22[i]
    arcond1.append(cond1)
    cond1=list(arcond1)
print("cond 1 =",cond1) 

The current output is

cond 1 = [False, False]

The expected output is

cond 1 = [[[False, True, False, True, False]], [[False, False]]]

CodePudding user response:

As you have 3 nesting levels, use a nested list comprehension:

out = [[[c3>d3 for c3, d3 in zip(c2, d2)]
        for c2, d2 in zip(c1, d1)]
       for c1, d1 in zip(C22, D22)]

Output: [[[False, True, False, True, False]], [[False, False]]]

CodePudding user response:

You can solve your issue with that: a loop in a loop in a loop

C22 = [[[353.856161, 417.551036, 353.856161, 353.856161, 282.754301]], [[294.983702, 294.983702]]]

D22 = [[[423.81345923, 230.97804127, 419.14952534, 316.58460442, 310.81809094]], 
       [[423.81345923, 419.14952534]]]

final_res = []

cond = lambda a, b: a > b

for list_1, list_2 in zip(C22, D22):
  res1 = []
  for sub_list_1, sub_list_2 in zip(list_1, list_2):
    res2 = []
    for sub_sub_list_1, sub_sub_list_2 in zip(sub_list_1, sub_list_2):
      res2.append(cond(sub_sub_list_1, sub_sub_list_2))
    res1.append(res2)
  final_res.append(res1)

print(final_res)

CodePudding user response:

For a general approach, you can use the following function:

from typing import List, Union

InputType = Union[List[List], List[float]]
OutputType = Union[List[List], List[bool]]


def check_list_A_greater_than_B(A: InputType, B: InputType) -> OutputType:

    # some checks to validate input variables
    assert len(A) == len(B), "list A and B should be of same length"
    if not len(A):  # A and B are empty
        return []

    # if the list elements are sublists, we pass them through this function again
    # if they are floats, we compare them and return the results
    result = []
    for A_element, B_element in zip(A, B):
        # check if types match
        error_msg = (
            f"Element types of A ({type(A_element)}) "
              f"should match B ({type(B_element)})"
              f"\nA = {A} \nB= {B}"
        )
        assert type(A_element) == type(B_element), error_msg
        if isinstance(A_element, list):
            result.append(check_list_A_greater_than_B(A_element, B_element))
        elif isinstance(A_element, float):
            result.append(A_element > B_element)
        else:
            raise Exception(f"Unexpected type of A_element ({type(A_element)})")

    return result

This allows you to input lists with a variable number of sublists and nested levels.

Example usage (with C22 and D22 from your example):

check_list_A_greater_than_B(C22, D22)

outputs:

[[[False, True, False, True, False]], [[False, False]]]
  • Related