You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对嵌套列表按子列表首元素排序并提取首个重复元素组

Solution

To solve this problem, we can break it down into two core steps: sorting the nested list by the first element of each sublist, then identifying and extracting the first duplicate sublist along with all its occurrences.

Step 1: Sort the List by the First Element

First, we sort the input list so that all sublists starting with the same value are grouped together. This makes it much easier to spot and extract duplicates later. We use Python's built-in sorted() function with a custom key to target the first element of each sublist:

l = [[3,4], [2,3], [1,2], [1,3], [1,2]]
# Sort sublists based on their first element
sorted_list = sorted(l, key=lambda x: x[0])
# Result: [[1,2], [1,3], [1,2], [2,3], [3,4]]

Step 2: Find and Extract the First Duplicate Sublist

Once sorted, we need to locate the first sublist that appears more than once, then collect all instances of that sublist. Here are two straightforward approaches:

Approach 1: Using collections.Counter

This method leverages the Counter class to count occurrences of each sublist (we convert sublists to tuples since lists aren't hashable). We then find the first sublist with a count greater than 1:

from collections import Counter

# Count how many times each sublist appears (convert to tuple for hashing)
element_counts = Counter(tuple(sub) for sub in sorted_list)

# Identify the first sublist that has duplicates
target_element = None
for sublist in sorted_list:
    if element_counts[tuple(sublist)] > 1:
        target_element = sublist
        break

# Collect all instances of the target sublist
result = [sub for sub in sorted_list if sub == target_element]

print(result)  # Output: [[1,2], [1,2]]

Approach 2: Manual Tracking (No Imports)

If you prefer to avoid external libraries, you can track seen sublists manually using a dictionary:

seen = {}
target_element = None

for idx, sublist in enumerate(sorted_list):
    # Convert sublist to tuple to use as a dictionary key
    sub_tuple = tuple(sublist)
    if sub_tuple in seen:
        target_element = sublist
        break
    seen[sub_tuple] = idx

# Collect all instances of the target sublist
result = [sub for sub in sorted_list if sub == target_element]

print(result)  # Output: [[1,2], [1,2]]

Key Notes

  • Sorting Logic: The key=lambda x: x[0] ensures sublists are ordered by their first element, grouping like values together.
  • Duplicate Detection: Both methods efficiently find the first repeating sublist. Counter is concise, while manual tracking keeps things dependency-free.
  • Extraction: We filter the sorted list to gather all copies of the first duplicate sublist, producing the exact output you're looking for.

内容的提问来源于stack exchange,提问作者Nick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:51:03