Python列表元组迁移问题:基于姓名性别字段处理重复项
Efficiently Move Duplicate Tuples Between Lists
First, let's break down why your current approach isn't working:
- The line
name_fy = [(item[2] for item in list_first) and (item[3] for item in list_first)]doesn't create pairs of (name, gender) values. Instead, it generates a list containing a single generator object (sinceandreturns the last truthy expression here). You can't compare these generators directly to find matches. - Even if you fixed that, using nested loops to compare every pair would be inefficient (O(n*m) time complexity), which gets slow as your lists grow.
Here's a much more efficient approach using sets for fast lookups:
Step-by-Step Solution
Create a set of existing (name, gender) pairs from
list_first. Sets allow O(1) average-time lookups, which makes checking duplicates quick:# Extract (name, gender) pairs from list_first and store in a set existing_pairs = {(item[2], item[3]) for item in list_first}Identify tuples to move from
second_listthat match any pair in the set:# Collect all tuples in second_list that have a matching (name, gender) pair to_move = [tuple_item for tuple_item in second_list if (tuple_item[2], tuple_item[3]) in existing_pairs]Add the matched tuples to list_first:
list_first.extend(to_move)Update second_list to remove the moved tuples:
# Keep only tuples in second_list that don't have a matching pair second_list = [tuple_item for tuple_item in second_list if (tuple_item[2], tuple_item[3]) not in existing_pairs]
Full Working Code
Putting it all together with your sample data:
list_first = [(1, 2, 'Adam', 'Men', '3.5', '1'), (1, 2, 'Ewa', 'Women', '2', '1'), (1, 2, 'Adam', 'Men', '4', '2')] second_list = [(2, 5, 'Jack', 'Men', '3.5', '1'), (1, 3, 'Chris', 'Women', '5', '2'), (10, 22, 'Adam', 'Men', '42', '11')] # Step 1: Create set of existing (name, gender) pairs existing_pairs = {(item[2], item[3]) for item in list_first} # Step 2: Find tuples to move to_move = [item for item in second_list if (item[2], item[3]) in existing_pairs] # Step 3: Add to list_first list_first.extend(to_move) # Step4: Update second_list second_list = [item for item in second_list if (item[2], item[3]) not in existing_pairs] # Verify results print("Updated list_first:", list_first) print("Updated second_list:", second_list)
Output
Updated list_first: [(1, 2, 'Adam', 'Men', '3.5', '1'), (1, 2, 'Ewa', 'Women', '2', '1'), (1, 2, 'Adam', 'Men', '4', '2'), (10, 22, 'Adam', 'Men', '42', '11')] Updated second_list: [(2, 5, 'Jack', 'Men', '3.5', '1'), (1, 3, 'Chris', 'Women', '5', '2')]
This approach runs in O(n + m) time (where n is the length of list_first and m is length of second_list), which is much more efficient than nested loops.
内容的提问来源于stack exchange,提问作者user9373369
相关产品推荐
相关产品推荐

