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

如何在Python中创建长度为n-1的列表及基于已有列表生成短1位的列表

解决方法:创建指定长度的独立空列表集合

Got it, let's break down your needs into clear, actionable steps:

1. 基于现有months列表生成长度为len(months)-1的空列表集合

You already know [[] for i in months] creates a list of independent empty lists matching the length of months. To get a version with length len(months)-1, here are two straightforward approaches:

  • Option 1: Slice the original list for derivation
    Use Python's slice syntax months[:-1] to grab all elements of months except the last one, then run the list comprehension on this sliced subset:

    months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
    newList = [[] for i in months[:-1]]
    # Result: [[], [], [], [], []] (length 5, which is 6-1)
    
  • Option 2: Loop directly with the target length
    Since we know the target length is len(months)-1, we can skip slicing the original list and use range() to generate the exact number of iterations. Using _ as the loop variable is a common Python convention here, since we don't need to use its value:

    months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
    newList = [[] for _ in range(len(months)-1)]
    # Result is the same: [[], [], [], [], []]
    

2. Directly create a list of length n-1 (for any specified n)

If you don't need to rely on an existing list and just want to generate a list of n-1 independent empty lists, the core logic stays the same—use a list comprehension with range():

n = 6  # Replace this with any number you need
newList = [[] for _ in range(n-1)]
# When n=6, this gives [[], [], [], [], []]

⚠️ Critical Note: Never use [[]]*(n-1) for this task! This syntax creates a list where all "empty lists" are references to the same object. Modifying one will modify all of them:

bad_list = [[]]*5
bad_list[0].append(1)
print(bad_list)  # Output: [[1], [1], [1], [1], [1]]

The list comprehension method avoids this issue by creating a brand new empty list for each iteration.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:12:07