在Python中重新分配列表

0 投票
3 回答
625 浏览
提问于 2025-04-15 12:45

好的,这是我的问题。我正在尝试做这样的事情:

for i in big_list:
   del glist[:]

   for j in range(0:val)
         glist.append(blah[j])

我的想法是重置这个列表,然后把它用来存储下一组数据点。

问题是,不知道为什么,如果第一个列表有3个点,

glist[0]
glist[1]
glist[2]

下一个列表会从索引3开始,并把最后3个元素存储在那些索引里。

glist[0] = 4th elem of new list
glist[1] = 5th elem of new list
glist[2] = 6th elem of new list
glist[3] = 1st elem of new list
glist[4] = 2nd elem of new list
glist[5] = 3rd elem of new list

我确定这是分配空间的问题。但是我该怎么做才能实现这个 del g_list[:] 这样结果是,

glist[0] = 1st elem of new list
glist[1] = 2nd elem of new list
glist[2] = 3rd elem of new list
glist[3] = 4th elem of new list
glist[4] = 5th elem of new list
glist[5] = 6th elem of new list

在循环中分配变量不是一个选项。有什么想法吗?

3 个回答

1

你可以试试

glist=[]
1

del glist[:] 这个命令可以很好地清空一个列表。你需要把你的具体代码给我们看一下。下面的例子中,你描述的情况并没有发生。在 del a[:] 之后使用 append 命令会把新加的项目放在列表的第一个位置,也就是索引0。

>>> a = [1,2,3]
>>> del a[:]
>>> a
[]
>>> a.append(4)
>>> a
[4]
5

del glist[:] 改成 glist = []。在Python里,你不需要去“重复使用”或者“重新分配”什么的,垃圾回收器会帮你处理这些。

另外,你在两个循环里都用'i'作为循环变量。这样迟早会让你搞混的。:)

撰写回答