以下是一个示例代码,演示如何遍历嵌套列表并检索属性:
def retrieve_attribute(nested_list, attribute):
for item in nested_list:
if isinstance(item, list):
retrieve_attribute(item, attribute)
elif hasattr(item, attribute):
print(f"{attribute}: {getattr(item, attribute)}")
# 示例嵌套列表
nested_list = [['apple', 'banana'], ['orange', 'grape'], ['watermelon', 'kiwi']]
# 获取嵌套列表中字符串元素的长度属性
retrieve_attribute(nested_list, 'length')
在上面的代码中,retrieve_attribute
函数接受一个嵌套列表和一个属性参数。它使用isinstance
函数来检查列表中的元素是否为列表类型,如果是,则递归调用retrieve_attribute
函数继续遍历该子列表。否则,使用hasattr
函数检查元素是否具有指定的属性。如果有,使用getattr
函数获取该属性的值,并进行打印或其他处理。
在示例中,嵌套列表nested_list
包含多个子列表,每个子列表包含字符串元素。函数通过检索字符串元素的length
属性并进行打印,来演示了如何遍历嵌套列表并检索属性。
上一篇:遍历嵌套列表
下一篇:遍历嵌套列表并进行过滤