Python中如何去除两个关联列表的重复配对项?
Hey there! Let's sort out this duplicate pair issue for your email content. The goal is to keep only the first occurrence of each (list_I element, list_II element) pair, right? Here's a straightforward, efficient way to do this in Python:
Step-by-Step Solution
First, we'll track which pairs we've already seen using a set (since set lookups are fast), then iterate through both lists in lockstep, building our new lists only with unique, first-seen pairs.
# Your original lists (note: I've added quotes to string values for valid Python syntax) list_I = [123, 453, 444, 555, 123, 444] list_II = ['A', 'A', 'B', 'C', 'A', 'B'] # Initialize a set to track seen pairs, plus empty new lists seen_pairs = set() New_list_I = [] New_list_II = [] # Iterate through paired elements from both lists for val_i, val_ii in zip(list_I, list_II): current_pair = (val_i, val_ii) # Only keep the pair if we haven't seen it before if current_pair not in seen_pairs: seen_pairs.add(current_pair) New_list_I.append(val_i) New_list_II.append(val_ii) # Verify the results print(New_list_I) # Output: [123, 453, 444, 555] print(New_list_II) # Output: ['A', 'A', 'B', 'C']
How This Works
zip(list_I, list_II)lets us loop through corresponding elements from both lists at the same time, creating pairs like(123, 'A'),(453, 'A'), etc.- The
seen_pairsset keeps track of every pair we've already added to our new lists. Since sets don't allow duplicates, checking if a pair exists is quick and efficient. - We only add elements to
New_list_IandNew_list_IIwhen their pair is encountered for the first time, which preserves the original order while eliminating duplicate pairs.
If your list_II values are not strings (e.g., custom objects), just make sure they're hashable (most built-in types like numbers, strings, tuples are). If you're working with custom classes, you'll need to implement the __hash__ and __eq__ methods for this approach to work.
内容的提问来源于stack exchange,提问作者GND

