使用zip合并两个列表为键值对时键重复致结果异常的技术求助
First, let's break down why you're only getting two key-value pairs when using zip() with a dictionary: dictionaries in Python require unique keys. When you convert zipped pairs directly to a dict, every time a duplicate key (like "Inside the area") comes up, it overwrites the previous value tied to that key. That's why you're left with just the last occurrence of each label paired with its lat value.
Since your goal is to collect all lat values marked as "Inside the area", here are a few straightforward solutions tailored to your needs:
1. List Comprehension (Quickest for Your Exact Goal)
If you only need the list of lat values in the area, a list comprehension is the simplest approach. It loops through zipped label-lat pairs and filters exactly what you want:
# Example input lists labels = ["Inside the area", "Outside the area", "Inside the area", "Inside the area", "Outside the area"] lats = [77.2167, 77.2, 78.123, 76.987, 77.5] # Filter lat values where label is "Inside the area" inside_lats = [lat for label, lat in zip(labels, lats) if label == "Inside the area"] print(inside_lats) # Output: [77.2167, 78.123, 76.987]
This gives you exactly the list you need with minimal code.
2. Use defaultdict to Group All Labels
If you might later need access to "Outside the area" lat values too, or want to keep all labels mapped to their respective lat lists, use collections.defaultdict to automatically handle duplicate keys by appending values to a list:
from collections import defaultdict label_to_lats = defaultdict(list) # Iterate through zipped pairs and build the mapping for label, lat in zip(labels, lats): label_to_lats[label].append(lat) # Get just the inside lat values inside_lats = label_to_lats["Inside the area"] print(inside_lats) # Output: [77.2167, 78.123, 76.987] # You can also grab outside values if needed later outside_lats = label_to_lats["Outside the area"] print(outside_lats) # Output: [77.2, 77.5]
This approach keeps all your data organized in one structure, making it easy to retrieve groups down the line.
3. Manual Dictionary Handling (No External Libraries)
If you don't want to import collections, you can manually check for existing keys and append values to lists:
label_to_lats = {} for label, lat in zip(labels, lats): if label not in label_to_lats: label_to_lats[label] = [] label_to_lats[label].append(lat) inside_lats = label_to_lats["Inside the area"] print(inside_lats) # Same output as above
This does the same job as defaultdict but requires a bit more code to initialize lists for new keys.
Pick the method that fits your use case best—for just grabbing inside lat values, the list comprehension is your fastest bet!
内容的提问来源于stack exchange,提问作者Raghav Patnecha

