【问题标题】:How to extract certaion values in the list using Python? [closed]如何使用 Python 提取列表中的某些值? [关闭]
【发布时间】:2021-05-18 02:42:31
【问题描述】:

我有以下清单:

URLs = [ 
  { "category": "A12",
    "base_url": "https://stackoverflow.com",
    "endpoints" : [ 
        { "name": "Online", "path": "/a2"},
        { "name": "Offline ", "path": "/b2"}
    ]
  },
  { "category": "A13",
    "base_url": "https://google.com",
    "endpoints" : [ 
        { "name": "Online", "path": "/abc1"},
        { "name": "Offline", "path": "/abc2"}
    ]
  },
  { "category": "A14",
    "base_url": "http://stackover.com",
    "endpoints" : [ 
        { "name": "Check", "path": "/bbc3"}
    ]
  }
]

我想仅从列表中提取基本 url 和端点路径并打印或另存为另一个变量。输出应如下所示:

https://stackoverflow.com/a2
https://stackoverflow.com/b2
https://google.com/abc1
https://google.com/abc2
http://stackover.com/bbc3

我该怎么做?

【问题讨论】:

  • 这是多个小操作的组合:1)如何循环遍历列表的每个元素,2)如何访问字典中特定键的值,3)重复1和2对于“端点”的内部列表,4)如何将 2 个字符串连接在一起,5)如何将结果存储在列表中。试一试,一步一步来。打印出每个操作的结果,看看你在每一步都有什么。

标签: python list url extract endpoint


【解决方案1】:

列表理解会给你想要的输出。

URLs = [ 
  ...
]

res = [i["base_url"] + j["path"] for i in URLs for j in i["endpoints"]]

结果如下所示:

['https://stackoverflow.com/a2', 'https://stackoverflow.com/b2', 'https://google.com/abc1', 'https://google.com/abc2', 'http://stackover.com/bbc3']

【讨论】:

    【解决方案2】:

    所以你有一个list,在列表中有一个dictionary。那将是最简单的方法:

     for url in URLs:
            print(url["base_url"])
    

    【讨论】:

      【解决方案3】:

      解决办法

      output = []
      
      for url_map in URLs:
          for endpoint in url_map['endpoints']:
              output.append(url_map['base_url'] + endpoint['path'])
      

      【讨论】:

        猜你喜欢
        • 2019-01-06
        • 1970-01-01
        • 2019-11-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多