【python】返回所有匹配项的第一个元素、第二个元素。。。
每个元素是一个二元组 (key, resource)
results 是一个包含所有匹配项的列表,每个元素是一个二元组 (key, resource)。
[item[0] for item in results] 是一个列表推导式,表示取出每个二元组的第一个元素(即 key),所以它返回所有匹配项的 key 列表。
分析
item[0]
表示获取元组或列表 item
的第一个元素。
在你的代码中,results
是一个包含元组的列表,每个元组通常形如 (key, resource)
,所以 item[0]
就是 key
,item[1]
是 resource
。
返回 [item[0] for item in results]
就是返回所有匹配项的 key 列表。
[item[1] for item in results]
means returning a list of the second element (index 1) from each tuple in the results
list. In your context, results
contains tuples of (key, resource)
, so this expression returns a list of all matched resource
objects.
代码
def find_id_and_res_by_prefix(test_id_prefix):# Example: Find resources with ID starting with a prefixmatching_resources = find_id_by_prefix(test_id_prefix, resource_id_index)print(f"\nFound {len(matching_resources)} resources with ID starting with '{test_id_prefix}':")results = []for key, resource in matching_resources.items():print(f"Key: {key}")print(f"Resource: {resource}\n")results.append((key, resource))if len(results) == 1:return 1, results[0][0], results[0][1]elif len(results) > 1:return len(results), [item[0] for item in results],[item[1] for item in results] else:return 0, None, []