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

Python输入列表移除非唯一元素:Springboard入学测试代码异常求助

Hey there! Let's break down your questions and fix that tricky code issue you're facing.

移除非唯一元素:正确方法 & 代码问题排查

问题1:如何从input输入的列表中移除非唯一元素?

The core goal here is to keep only elements that appear at least twice in your input list. Here's a straightforward step-by-step approach:

  • Grab the user's input string with input(), then split it into a list using split() (this handles space-separated values by default).
  • Count how many times each element appears in the list (we can use collections.Counter for this—it's built specifically for frequency counting).
  • Filter the original list to keep only elements that have a count ≥2.

Here's a working example:

from collections import Counter

def keep_duplicates(input_str):
    num_list = input_str.split()
    element_counts = Counter(num_list)
    # List comprehension to filter elements that appear more than once
    return [num for num in num_list if element_counts[num] >= 2]

user_input = input("Enter your space-separated numbers: ")
print(keep_duplicates(user_input))

For example, if you input 1 2 2 3 3 3, this will return ['2', '2', '3', '3', '3']—keeping all instances of elements that repeat.

问题2:Why is your code skipping some non-unique elements?

Let's look at your original code first:

def non_unique_numbers(line):
    for i in line:
        if line.count(i) < 2:
            line.remove(i)
    return line

The root problem is you're modifying the list while you're iterating over it. This messes up the loop's indexing, causing some elements to be skipped entirely. Let's walk through a concrete example to see why:

Suppose your input list is ['1', '2', '1', '3', '4']:

  1. The loop starts with i='1'—since it appears twice, we leave it alone.
  2. Next, i='2'—it only appears once, so we remove it. Now the list becomes ['1', '1', '3', '4'].
  3. The loop moves to the next index (originally index 2, which was '1' in the original list). But since we modified the list, the element at this index is now '3'. We check its count (1), remove it, and the list becomes ['1', '1', '4'].
  4. The loop tries to move to index 3, but the list is now only 3 elements long—so the loop ends. The element '4' (which is unique) is never checked and stays in the list.

That's why you're seeing some non-unique elements get left behind!

Fixes for your code

You have two solid options to fix this:

Option 1: Iterate over a copy of the list

By looping through a duplicate of your original list, modifying the original won't affect the iteration. Here's how to adjust your code:

def non_unique_numbers(line):
    # Iterate over a copy of the list (list(line) creates a duplicate)
    for i in list(line):
        if line.count(i) < 2:
            line.remove(i)
    return line

lin = input('go on then')
line = lin.split()
print(non_unique_numbers(line))

Option 2: Use a list comprehension (more efficient)

Calling line.count(i) every time loops through the entire list each time, which is slow for large lists. Using Counter like we did earlier is much more efficient:

from collections import Counter

def non_unique_numbers(line):
    element_counts = Counter(line)
    return [num for num in line if element_counts[num] >= 2]

lin = input('go on then')
line = lin.split()
print(non_unique_numbers(line))

Both fixes will correctly remove all non-unique elements and keep every instance of elements that repeat.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:02:07