如何基于预定义列表list1调整去重后list2的输出顺序?
Solution: Reorder Deduplicated List to Match Reference List
Here's a straightforward way to get your deduplicated list aligned with the order of list1:
Step-by-Step Implementation
- Deduplicate
list2: Convert it to a set—sets automatically eliminate duplicate elements, which is perfect for this step. - Filter & Reorder: Iterate through
list1and keep only elements that exist in the deduplicated set fromlist2. This ensures we followlist1's order while only including elements present inlist2.
Code Example
list1 = ['f','l','a','m','e','s'] list2 = ['e','e','f','a','s','a'] # Create a set of unique elements from list2 unique_list2 = set(list2) # Build x by following list1's order and filtering for elements in unique_list2 x = [item for item in list1 if item in unique_list2] print(x) # Output: ['f', 'a', 'e', 's']
Why This Works
- Fast Membership Checks: Using a set for
unique_list2makes checking if an element exists quick (O(1) time complexity), so this method stays efficient even with longer lists. - Strict Order Preservation: By looping directly through
list1, we enforce exactly the sequence you want. Any elements inlist1that aren't present inlist2(like 'l' and 'm' here) get automatically excluded.
Alternative Explicit Loop
If you prefer a more verbose approach over list comprehensions, here's the same logic written as a plain loop:
x = [] unique_list2 = set(list2) for item in list1: if item in unique_list2: x.append(item)
This produces the exact same result—just in a format that might feel more intuitive if you're new to Python.
内容的提问来源于stack exchange,提问作者Sindhu Laksh
相关产品推荐
相关产品推荐

