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

如何移除列表中首子串重复的元素并保留指定项?

Solution for Removing Duplicate List Elements Based on Prefix

Hey there! Let's work through how to solve this problem where we need to deduplicate list elements based on the substring before the first comma, keeping only the element containing "655" when duplicates exist.

Step-by-Step Approach

Here's the core logic we'll follow:

  1. Group elements by their prefix: Split each string at the first comma and use that substring as a key to group all matching elements.
  2. Process each group:
    • If a group has only one element, keep it as-is.
    • If a group has multiple elements, filter and keep only the one that includes "655".

Python Code Example

Let's turn this logic into working code using Python (a common choice for such data processing tasks):

from collections import defaultdict

# Your original list (formatted into proper string elements)
original_list = ["968934,655,814", "968934,123,814", "123456,789,012"]

# Step 1: Group elements by the substring before the first comma
element_groups = defaultdict(list)
for item in original_list:
    # Split the string and take the first part as the grouping key
    prefix_key = item.split(',')[0]
    element_groups[prefix_key].append(item)

# Step 2: Process each group to build the result
final_list = []
for key, items in element_groups.items():
    if len(items) == 1:
        # No duplicates, keep the only element
        final_list.append(items[0])
    else:
        # Find the element containing "655" and add it to the result
        for item in items:
            if "655" in item:
                final_list.append(item)
                break  # Stop searching once we find the match (assuming one per group)

print(final_list)
# Output: ['968934,655,814', '123456,789,012']

Explanation

  • Grouping with defaultdict: This makes it easy to automatically create a list for each unique prefix key, so we don't have to handle empty groups manually.
  • Splitting strings: Using split(',')[0] gives us the substring before the first comma, which is our grouping criteria.
  • Handling duplicates: For groups with multiple elements, we loop through to find the one with "655"—the break ensures we stop once we find it (since your example implies only one such element per duplicate group).

If you need to handle edge cases like multiple elements in a group containing "655", you can adjust the code to collect all of them instead of breaking after the first match.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:49:21