【问题标题】:Python - Nested lists - Call nested indexes of sublistPython - 嵌套列表 - 调用子列表的嵌套索引
【发布时间】:2022-01-14 14:58:17
【问题描述】:

我有一个这样的嵌套子列表:

my_list = {'active': {'type': 'boolean', 'string': 'Active'}, 'name': {'type': 'char', 'string': 'Title'}, 'description': {'type': 'html', 'string': 'Description'}, 'priority': {'type': 'selection', 'string': 'Priority'}, 'product': {'type': 'char', 'help': 'Selected product by user', 'string': 'Product'}}

您会注意到子列表的内容并不总是相同:'type''string',有时还有'help'

我可以运行一个基本的for 循环来显示列表的元素:

for i in my_list:
    print(i)

返回给我:

active
name
description
priority
product

但是我怎样才能遍历子列表的项目呢?我想我需要嵌套另一个 for 循环。

我想显示具体信息,例如:

- Active: active, boolean
- Title: name, char
- Description: description, html
- Priority: priority, selection
- Product: product, char, Selected product by user

【问题讨论】:

  • 那些是字典,不是列表。使用.items() 遍历字典中的键值对
  • 您想要的输出与输入不匹配?请添加有关您要显示的内容的更多详细信息
  • for j in my_list[i]: 将迭代内部字典

标签: python multidimensional-array


【解决方案1】:

所以第一件事。这不是一个列表。这是一个嵌套字典或 Python 中的 dict。这是一个向您展示差异的链接:Difference between List and Dictionary in Python

您可以通过它的键名引用一个 dict 元素。例如:

my_list['active'] # {'type': 'boolean', 'string': 'Active'}

或者当您不确定特定密钥是否存在时,请使用get() 方法。如果没有指定名称的键,它将返回None。要获得您想要的输出,这里有一个快速的解决方案:

for elem in my_list:
    output = f'{my_list[elem]["string"]}: {elem}, {my_list[elem]["type"]}'
    is_help = my_list[elem].get("help")
    if is_help:
        output = f'{output}, {is_help}'
    print(output)

这将被打印出来:

Active: active, boolean
Title: name, char
Description: description, html
Priority: priority, selection
Product: product, char, Selected product by user

【讨论】:

  • 很抱歉列表和字典之间的混淆。 get() 方法就是这样,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-18
  • 2019-01-05
  • 2011-01-25
  • 1970-01-01
相关资源
最近更新 更多