python - 列表结构比较

标签 python list

任务是编写一个函数same-struct_as,它返回 TrueFalse 当需要列表比较嵌套结构时。

例如:

should return True same_structure_as([ 1, 1, 1 ], [ 2, 2, 2 ] ) same_structure_as([ 1, [ 1, 1 ] ], [ 2, [ 2, 2 ] ] )

should return False  same_structure_as([ 1, [ 1, 1 ] ], [ [ 2, 2 ], 2 ] ) same_structure_as([ 1, [ 1, 1 ] ], [ [ 2 ], 2 ] )

我的代码如下所示:

#!/usr/bin/python
# -*- coding: utf-8 -*-


def same_structure_as(original, other):
    count = 0
    if len(original) == len(other):
        for i in range(0, len(original) - 1):
            if isinstance(original[i], int) == isinstance(other[i],
                    int):
                count += 1
            elif len(original[i]) == len(other[i]):
                count += 1
    else:
        return False

    if count == len(original) - 1:
        return True

此代码遍历两个列表的每个元素,并检查它们是否是整数或子列表(具有相同的元素)。当我运行它时,我收到此错误:

elif len(original[i])==len(other[i]):TypeError: object of type 'int' has no len()

最佳答案

在使用 Python 设计程序时,我始终遵循的一条规则是永远不要信任用户。这意味着始终检查您获得的输入的类型,确保您获得的参数具有有效值...

在第一个 if 中,您测试了这两项是否都是 int,但之后您不能假设这两项都不是。如果一个是 int,另一个是列表(这里正是这种情况)怎么办?

您应该添加更多类型检查,如下所示:

def same_structure_as(original, other):
    count = 0
    if len(original) == len(other):
        for i in range(0, len(original) - 1):
            if isinstance(original[i], int) == isinstance(other[i],
                    int):
                count += 1
            elif (isinstance(original[i], list) and
                  isinstance(other[i], list) and
                  len(original[i]) == len(other[i])):
                count += 1
    else:
        return False

    if count == len(original) - 1:
        return True

话虽这么说,有可能(也许更好)避免运行整个循环并在第一次遇到差异时停止:

def same_structure_as(original, other):

    # This avoids to make useless computations when they are not necessary
    if not isinstance(original, list) or not isinstance(other, list)
        # You can even raise a TypeError, to inform the user
        # that they should make sure to provid two lists
        return False

    if len(original) != len(other):
        return False

    for index in range(len(original)):
        if isinstance(original[index], list) and isinstance(other[index], list):
            if type(original[index]) != type(other[index]):
                # This would happen for example with [1, ...] and [[1], ...]
                return False
            if len(original[index]) != len(other[index]):
                # This would happen for example with [[1, 1], ...] and [[1], ...]
                return False

    return True

关于python - 列表结构比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59898566/

相关文章:

python - 在 Python 中将大文件(25k 条目)加载到 dict 中很慢?

python - 让 PyQt5 标签在发送 http 请求时动态更新

python - 如果字符串存在于列表中,则替换整个数据框中的字符串

python - 如何使用 python 分割列表中的特定单词

java - Generic List 的 Generic List 的初始化

python - 检索一行 2 for 循环内最里面的值?

python - python中的多线程文件下载并在shell中更新下载进度

python - 如何找到哪个pip包拥有一个文件?

css - 我可以使用 list-style-type 到 div 标签吗?

python - 清理数据 : How to iterate through a list find if item contains a string, 空白或空白并在 Python 中删除该项目