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中的迭代器、生成器与列表解析用法

迭代器:初探 上一章曾经提到过,其实for循环是可用于任何可迭代的对象上的。实际上,对Python中所有会从左至右扫描对象的迭代工具而言都是如此,这些迭代工具包括了for循环、列表解析、...

python和bash统计CPU利用率的方法

本文实例讲述了python和bash统计CPU利用率的方法。分享给大家供大家参考。具体如下: 开始的时候写了一个 bash 的实现; 因为最近也在学习 python ,所以就尝试着用 p...

python3.6+django2.0+mysql搭建网站过程详解

python3.6+django2.0+mysql搭建网站过程详解

之前用过python2.7版本,改用3.6版本发现很多语法发生了变化。 在templates里新建一个html文件,命名为index.html作为要测试的界面, 新建一个应用,Tools...

python多线程操作实例

python多线程操作实例

一、python多线程 因为CPython的实现使用了Global Interpereter Lock(GIL),使得python中同一时刻只有一个线程在执行,从而简化了python解释...

python实现图片文件批量重命名

python实现图片文件批量重命名

本文实例为大家分享了python实现文件批量重命名的具体代码,供大家参考,具体内容如下 代码: # -*- coding:utf-8 -*- import os class I...