如何使用 Python 提取列表中的某些值?
How to extract certaion values in the list using Python?
我有以下列表:
URLs = [
{ "category": "A12",
"base_url": "https://whosebug.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://whosebug.com/a2
https://whosebug.com/b2
https://google.com/abc1
https://google.com/abc2
http://stackover.com/bbc3
我该怎么做?
所以你有一个 list
并且在列表中有一个 dictionary
。这将是最简单的方法:
for url in URLs:
print(url["base_url"])
这是解决方案
output = []
for url_map in URLs:
for endpoint in url_map['endpoints']:
output.append(url_map['base_url'] + endpoint['path'])
列表理解会给你想要的输出。
URLs = [
...
]
res = [i["base_url"] + j["path"] for i in URLs for j in i["endpoints"]]
结果如下所示:
['https://whosebug.com/a2', 'https://whosebug.com/b2', 'https://google.com/abc1', 'https://google.com/abc2', 'http://stackover.com/bbc3']
我有以下列表:
URLs = [
{ "category": "A12",
"base_url": "https://whosebug.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://whosebug.com/a2
https://whosebug.com/b2
https://google.com/abc1
https://google.com/abc2
http://stackover.com/bbc3
我该怎么做?
所以你有一个 list
并且在列表中有一个 dictionary
。这将是最简单的方法:
for url in URLs:
print(url["base_url"])
这是解决方案
output = []
for url_map in URLs:
for endpoint in url_map['endpoints']:
output.append(url_map['base_url'] + endpoint['path'])
列表理解会给你想要的输出。
URLs = [
...
]
res = [i["base_url"] + j["path"] for i in URLs for j in i["endpoints"]]
结果如下所示:
['https://whosebug.com/a2', 'https://whosebug.com/b2', 'https://google.com/abc1', 'https://google.com/abc2', 'http://stackover.com/bbc3']