繁体   English   中英

比较Python中两个列表的子列表

[英]Comparing sublists of two lists in Python

我有两个包含许多子列表的列表C22D22 我想比较每个子列表的元素并打印它是否满足标准,即C22的每个子列表的元素大于D22的每个子列表的元素。 我介绍了当前和预期的输出。

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) 

当前output是

cond 1 = [False, False]

预期的 output 是

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

由于您有 3 个嵌套级别,请使用嵌套列表理解:

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]]]

你可以解决你的问题:循环中的循环

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)

对于一般方法,您可以使用以下 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

这允许您输入具有可变数量的子列表和嵌套级别的列表。

用法示例(使用示例中的 C22 和 D22):

check_list_A_greater_than_B(C22, D22)

输出:

[[[False, True, False, True, False]], [[False, False]]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM