在Python中创建新的列表对象

14 投票
6 回答
61419 浏览
提问于 2025-04-15 14:34

我刚开始学习Python,想要在Python中创建一个新的列表对象。

我的代码:

recordList=[]

mappedDictionay={}

sectionGroupName= None

for record in recordCols:
    item = record
    print item

    if not sectionGroupName == record[0]:
        sectionGroupName = record[0]
        del recordList[0:] # Here I want to create new list object for recordList
        recordList.append(item)
        mappedDictionay[sectionGroupName] = recordList
    else:
        recordList.append(tempItem)

6 个回答

4

不要使用 del。就这样。它是一个“高级”的东西。

from collections import defaultdict

mappedDictionay= defaultdict( list ) # mappedDictionary is a poor name
sectionGroupName= None

for record in recordCols:
    mappedDictionay[record[0]].append( record )
7

Python 是一种会自动管理内存的编程语言,也就是说它会自动清理不再使用的东西,像垃圾一样。只需要输入

recordList = []

你就会得到一个新的空列表。

20

你的问题有点难懂,特别是你的代码格式乱了。不过,创建新的列表对象其实很简单。下面这段代码是把一个新的列表对象赋值给变量 recordList:

recordList = list()

你也可以使用

recordList = []

在这种情况下,[] 和 list() 是等价的。

撰写回答