如何在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 syntaxmonths[:-1]to grab all elements ofmonthsexcept 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 islen(months)-1, we can skip slicing the original list and userange()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

