任务是编写一个函数same-struct_as,它返回 True 或 False 当需要列表比较嵌套结构时。
例如:
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/