Python 列表的清空方式

yipeiwu_com6年前Python基础

情况列表的操作:

del list[:]

list=[]

list[:]=[]

def func(L):                                  
  L.append(1)
  print L
  #L[:]=[]
  #del L[:]
  L = []
  print L
 
L=[]
func(L)
print L

输出结果:

[1]

[]

[1]

分析:L是可变数据类型,L作为参数,函数内对L的改变,是可以反映到函数外的L中的,执行L.append(1),是在操作,函数外L所占据的那块内存,然后执行L =[],(函数内的L),想当于L指向了另外一个空间。所以,func(L),print L,输出[1]。

其实函数的本意是将参数L指向的内存清空,用L=[],并不能清空L指向的内存

def func(L):
  L.append(1)                                 
  print L
  L[:]=[]
  #del L[:]
  #L = []
  print L
 
L=[]
func(L)
print L

输出结果:

[1]
[]
[]

L[:]=[]:把L对应的内存清空

def func(L): 

  L.append(1)
  print L
  #L[:]=[]
  del L[:]
  #L = []
  print L
 
L=[]
func(L)
print L

分析:

del L[:] 的效果跟L[:]=[]的效果是一样的。

python 赋值,往往是通过指针完成的,a=b,只是让a指向了b,并未把b的内容拷贝到a

def func(L):                                  
  L.append(1)
  print L
  print id(L)
  #L[:]=[]
  #del L[:]
  L = []
  print id(L)
  print L
 
L=[]
func(L)
print L

输出结果:

31460240

31460168

很明显:通过赋值L=[]后,L指向的内存完全不一致了。

类似于c++的引用赋值。

Python 赋值都是引用赋值,相当于使用指针来实现的另一个例证

list =[]                                    
next = [None,None]
for i in range(10):
  next[0] = i 
  #print id(i)
  #print id(next[0])
  next[1] = i 
  #print id(next)
  list.append(next)
 
print list

输出结果:

[[9, 9], [9, 9], [9, 9], [9, 9], [9, 9], [9, 9], [9, 9], [9, 9], [9, 9], [9, 9]]

跟我们想要的结果不一致

list.append(next),仅仅是把next的地址放到list 里面

我们整个for 循环就使用了一个next,只是每次for循环,都在初始的next上进行操作,本次的操作会覆盖上次的结果

list =[]                                    
next = [None,None]
for i in range(10):
  next[0] = i 
  #print id(i)
  #print id(next[0])
  next[1] = i 
  #print id(next)
  list.append(next)
 
print list
print id(list[0])
print id(list[1])

输出结果:

[[9, 9], [9, 9], [9, 9], [9, 9], [9, 9], [9, 9], [9, 9], [9, 9], [9, 9], [9, 9]]

36166472

36166472

解决办法,每次for 循环都重新分配空间

list =[]                                    
for i in range(10):
  next = [None,None]
  next[0] = i 
  #print id(i)
  #print id(next[0])
  next[1] = i 
  #print id(next)
  list.append(next)
 
print list
print id(list[0])
print id(list[1])

输出结果:

[[0, 0], [1, 1], [2, 2], [3, 3], [4, 4], [5, 5], [6, 6], [7, 7], [8, 8], [9, 9]]

15060360

15059712

以上这篇Python 列表的清空方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python实现删除文件中含“指定内容”的行示例

本文实例讲述了Python实现删除文件中含指定内容的行。分享给大家供大家参考,具体如下: #!/bin/env python import shutil, sys, os darra...

Python设计模式之中介模式简单示例

Python设计模式之中介模式简单示例

本文实例讲述了Python设计模式之中介模式。分享给大家供大家参考,具体如下: Mediator Pattern:中介模式 中介模式提供了一系列统一的系统接口。此模式也被认为是行为模式,...

深入理解python中的浅拷贝和深拷贝

深入理解python中的浅拷贝和深拷贝

在讲什么是深浅拷贝之前,我们先来看这样一个现象: a = ['scolia', 123, [], ] b = a[:] b[2].append(666) print a print...

python简单线程和协程学习心得(分享)

python中对线程的支持的确不够,不过据说python有足够完备的异步网络框架模块,希望日后能学习到,这里就简单的对python中的线程做个总结 threading库可用来在单独的线程...

CentOS 7下Python 2.7升级至Python3.6.1的实战教程

CentOS 7下Python 2.7升级至Python3.6.1的实战教程

前言 大家应该都知道,Centos是目前最为流行的Linux服务器系统,其默认的Python 2.x,但是根据python社区的规划,在不久之后,整个社区将向Python3迁移,且将不在...