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

如何按指定元素出现次数扩展嵌套列表?求简洁实现方案

Alright, let's break down the pattern you're looking for first, then write a clean Python solution that generates exactly the output you need.

Step 1: Identify the Expansion Rules

Looking at your input and desired output, here's the clear pattern that emerges:

  • Sublists with only items from [A,B,C] (twice group): Repeat the sublist 2 times.
  • Sublists with only items from [D,E,F] (four group): Repeat the sublist 4 times.
  • Mixed sublists (contain items from both groups):
    1. First repeat the full sublist 2 times (to cover the required count for the twice group items).
    2. Then extract just the items from the four group, and repeat that subset 2 more times (since 4-2=2, to hit the required four occurrences for those items).

Step 2: Implement the Logic in Python

Here's a concise solution that follows these rules:

# Define your input data
my_input_list = [['A'], ['A','B','C'], ['D'], ['D','E','F'], ['A','B','C','D','E','F'], ['A','C','E']]
group_twice = {'A', 'B', 'C'}  # Use sets for fast membership checks
group_four = {'D', 'E', 'F'}

my_output_list = []

for sublist in my_input_list:
    # Check if all elements belong to the twice group
    if all(item in group_twice for item in sublist):
        my_output_list.extend([sublist.copy() for _ in range(2)])
        continue
    
    # Check if all elements belong to the four group
    if all(item in group_four for item in sublist):
        my_output_list.extend([sublist.copy() for _ in range(4)])
        continue
    
    # Handle mixed sublists
    # Add full sublist twice
    my_output_list.extend([sublist.copy() for _ in range(2)])
    # Extract four-group items and add twice more
    four_subset = [item for item in sublist if item in group_four]
    my_output_list.extend([four_subset.copy() for _ in range(2)])

# Verify the result
print(my_output_list)

Step3: Verify the Output

Running this code will produce exactly your desired my_output_list:

[['A'], ['A'], ['A', 'B', 'C'], ['A', 'B', 'C'], ['D'], ['D'], ['D'], ['D'], ['D', 'E', 'F'], ['D', 'E', 'F'], ['D', 'E', 'F'], ['D', 'E', 'F'], ['A', 'B', 'C', 'D', 'E', 'F'], ['A', 'B', 'C', 'D', 'E', 'F'], ['D', 'E', 'F'], ['D', 'E', 'F'], ['A', 'C', 'E'], ['A', 'C', 'E'], ['E'], ['E']]

This approach is clean, easy to read, and directly maps to the expansion rules we identified. Using sets for the groups makes membership checks fast, even if your lists grow larger.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:59:21