目标检测关联列表提取err为0的ID问题及字典适用性咨询
Absolutely—using a dictionary is a perfect fit here! It turns your list of scattered elements into a clean, key-value mapping where each id directly links to its corresponding err value, making it way easier to extract the data you need (and way more efficient if you ever need to look up or update values later).
Let me break this down with examples based on common structures your list_a might have:
Why a dictionary works better
Your core need is to associate each id with its err—that’s exactly what dictionaries are designed for. Unlike a list, where you’d have to loop through every element to find a specific id, a dictionary lets you look up an err by id in constant time (O(1)). Plus, it makes filtering for err == 0 straightforward.
Example 1: If your list elements are dictionaries
Suppose each entry in list_a is a dictionary with keys like id, coords, and err:
# Sample input list list_a = [ {"id": 1, "coords": (120, 340), "err": 0}, {"id": 2, "coords": (56, 78), "err": 2}, {"id": 3, "coords": (90, 100), "err": 0}, {"id": 4, "coords": (110, 220), "err": 5} ] # Convert list to a dictionary: map id to err id_err_map = {item["id"]: item["err"] for item in list_a} # Extract ids where err is 0 errorfree_id = [id for id, err in id_err_map.items() if err == 0] print(errorfree_id) # Output: [1, 3]
Example 2: If your list elements are tuples
If each entry is a tuple structured like (id, (x, y), err):
# Sample input list list_a = [ (1, (120, 340), 0), (2, (56, 78), 2), (3, (90, 100), 0), (4, (110, 220), 5) ] # Convert list to a dictionary id_err_map = {item[0]: item[2] for item in list_a} # Extract error-free ids errorfree_id = [id for id, err in id_err_map.items() if err == 0] print(errorfree_id) # Output: [1, 3]
What if you don’t want to convert to a dictionary?
You can still get the job done by looping directly through the list, but it’s less clean if you need to reuse the id-err mapping later:
errorfree_id = [] for item in list_a: # Adjust based on your element structure if item["err"] == 0: # Use item[2] == 0 if using tuples errorfree_id.append(item["id"]) # Or item[0] for tuples
A quick note on duplicate ids
If your list_a has duplicate id entries, the dictionary will automatically overwrite the earlier entries with the last one. If duplicates are possible, you’ll want to handle that first—for example, keeping the entry with the lowest err, or collecting all err values for an id.
That should solve your problem! Let me know if you need adjustments based on the exact structure of your list.
内容的提问来源于stack exchange,提问作者Venkat kamal

