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

如何基于元素全局出现次数条件删除列表元素

Solution: Remove Elements with Occurrences ≤2 from Nested Lists

Great that you’ve already got the element frequency dictionary ready—this makes the filtering step straightforward! Here’s how to leverage that dict to clean up your nested lists:

Step 1: Confirm Your Frequency Dictionary (Reference)

First, just to align, if you built your frequency count using Python, it might look something like this (using collections.Counter for simplicity):

from collections import Counter

A = [['a','b','c'],['b','d'],['c','d','e'],['c','e','f'],['b','c','e','g']]

# Flatten the nested list to count total occurrences
flat_elements = [item for sublist in A for item in sublist]
freq_dict = Counter(flat_elements)

# Resulting freq_dict: {'c':4, 'b':3, 'e':3, 'a':1, 'd':2, 'f':1, 'g':1}

Step 2: Filter Nested Lists Using the Frequency Dict

Now, use a nested list comprehension to iterate through each sublist and retain only elements that appear more than 2 times overall:

# Filter each sublist to keep elements with frequency >2
B = [[item for item in sublist if freq_dict[item] > 2] for sublist in A]

# Output B: [['b','c'],['b'],['c','e'],['c','e'],['b','c','e']]

How This Works

  • The outer list comprehension loops through each sublist in your original list A.
  • The inner comprehension checks each item in the current sublist against your freq_dict: if the item’s count is greater than 2, it’s kept in the new sublist.
  • This approach is efficient (O(n) time complexity where n is the total number of elements) and concise.

Notes

  • If you built your frequency dictionary manually (without Counter), this logic still works—just ensure your dict correctly maps each element to its total occurrence count across all sublists.
  • If any sublist ends up empty after filtering, it will remain as an empty list in B (you can add an extra check to remove empty sublists if needed, e.g., [sublist for sublist in B if sublist]).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:18:18