举例讲解Python中的list列表数据结构用法


Posted in Python onMarch 12, 2016

循环和列表

不管怎样,程序会做一些重复的事情,下面我们就用for循环打印一个列表变量。做这个练习的时候你必须自己弄懂它们的含义和作用。

在使用for循环之前,我们需要一个东西保存循环的值,最好的方法是使用一个列表,列表就是按照顺序保存数据的容器,不是很复杂,就是一种新的语法而已,结构像下面这样:

hairs = ['brown', 'blond', 'red']
eyes = ['brown', 'blue', 'green']
weights = [1, 2, 3, 4]

list以 [ 号开头,里面的元素以 , 号分隔,像函数的参数一样,然后以 ] 结束,python把所有这些包含在一个变量中。

下面我们来看一些list,并且循环打印它们:

the_count = [1, 2, 3, 4, 5] 
fruits = ['apples', 'oranges', 'pears', 'apricots'] 
change = [1, 'pennies', 2, 'domes', 3, 'quarters'] 
 
 
# this first kind of for-loop goes through a list 
for number in the_count: 
  print "This is count %d" % number 
 
 
# same as above 
for fruit in fruits: 
  print "A fruit of type: %s" % fruit 
 
 
# also we can go through mixed lists too 
# notice we have to use %r since we don't know what's in it 
for i in change: 
  print "I got %r" % i 
 
 
# we can also build lists, first start with an empty on 
elements = [] 
 
 
# then use the range function to do 0 to 5 counts 
for i in range(0, 6): 
  print "Adding %d to the list." % i 
  # append is a function that lists understand 
  elements.append(i) 
 
 
# now we can print them out too 
for i in elements: 
  print "Elements was: %d" % i

运行结果

root@he-desktop:~/mystuff# python ex32.py
This is count 1
This is count 2
This is count 3
This is count 4
This is count 5
A fruit of type: apples
A fruit of type: oranges
A fruit of type: pears
A fruit of type: apricots
I got 1
I got 'pennies'
I got 2
I got 'domes'
I got 3
I got 'quarters'
Adding 0 to the list.
Adding 1 to the list.
Adding 2 to the list.
Adding 3 to the list.
Adding 4 to the list.
Adding 5 to the list.
Elements was: 0
Elements was: 1
Elements was: 2
Elements was: 3
Elements was: 4
Elements was: 5

访问列表中的元素
List是非常有用的,前提是要知道怎么用,那么我们怎么访问列表中的元素呢?下面看看我们怎么访问列表的第一个元素的:

animals = ['bear', 'tiger', 'penguin', 'zebra']
bear = animals[0]

我们使用0去获得第一个元素?这是怎么工作的呢?因为python开始一个list是从0开始的,看上去很奇怪,但是有很多好处,暂且认为这是一个规定吧。

这就提现了我们用数字和程序用数字的不同。

想象一下,我们让这四个动物进行竞速比赛,然后按照他们的名次在list排列。如果你的朋友想知道谁赢了,那么他会说:”谁是第0名?“,当然不会,他会说:”谁是第一名?“

这里也说明了排序的重要性,没有第一就没有第二的说法,没有第二就没有第三。而且第0名也是不可能存在的,0就表示没有。我们怎么让没有去赢得比赛?这不合常理。我们把这些数字叫做有序的数字,因为它们有序的区别了一些东西。

当然,程序员不会想这些,因为他们可以从list中取出元素,对于程序员来说,上面的list就想一叠卡片。如果他们想要老虎,就取出老虎,想要斑马就取得斑马。想要随机的取得任何元素的话,就要给每个元素一个地址,或者说是一个索引,最好的办法是从0开始,然后按照顺序排列,这样我们就能随便取元素了,即使是第0个元素。

比如说,你想要第三个动物,那么你就可以用3减去1,得出索引2,那么就可以得到第三个动物了。

记住:序号==顺序1,基数==0

让我们做一个练习,通过我提供的序号和基数值写出相应的动物。记住,说第一,第二的时候表示序号,单单给出一个数字的时候表示基数。

animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
The animal at 1.
The 3rd animal.
The 1st animal.
The animal at 3.
The 5th animal.
The animal at 2.
The 6th animal.
The animal at 4.

回答的格式像这样:第一个动物是在0号,它是bear。

列表操作
如果我们只知道使用list的append方法,那么我们还不是真正知道这个函数的用法,让我们来看看它的使用方法吧。

当我们使用mystuff.append('hello')的时候发生了一系列的事情,让我们看看到底发生了什么:
python会先查看mystuff变量,看看是不是函数的参数,或者是全局变量,反正先要找到mystuff。
当mystuff使用 . 号的时候,会先看mystuff这个变量是什么,如果是list的话,会有很多它的方法可以使用。
使用append的时候,会去查找mystuff是不是有'append‘这个名称,有的话就直接拿来使用。
如果append后面有圆括号,那么就知道它是一个函数,像平时一样执行这个函数就好了,还会有额外的参数。
这个额外的参数就是mystuff,奇怪吧,但是python就是这样做的,最后函数是这样的:append(mystuff, 'hello')。
大多数情况下你不必知道这是怎么回事,但是在你遇到下面这个错误的时候就有帮助了:

root@he-desktop:~# python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Thing(object):
...   def test(hi):
...       print "hi"
... 
>>> a = Thing()
>>> a.test("hello")
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: test() takes exactly 1 argument (2 given)
>>>

下面的练习是将字符串和列表混合起来,看看我们能不能找出一些好玩的。

ten_things = "Apples Oranges Crows Telephone Light Sugar" 
 
 
print "Wait there's not 10 things in that list, let's fix that." 
 
 
stuff = ten_things.split(" ") 
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"] 
 
 
while len(stuff) != 10: 
  next_one = more_stuff.pop() 
  print "Adding:", next_one 
  stuff.append(next_one) 
  print "Thing's %d items now." % len(stuff) 
 
 
print "There we go:", stuff 
 
 
print "Let's do some things with stuff." 
 
 
print stuff[1] 
print stuff[-1] # 
print stuff.pop() 
print ' '.join(stuff) 
print '#'.join(stuff[3:5])

运行结果

root@he-desktop:~/mystuff# python ex38.py
Wait there's not 10 things in that list, let's fix that.
Adding: Boy
Thing's 7 items now.
Adding: Girl
Thing's 8 items now.
Adding: Banana
Thing's 9 items now.
Adding: Corn
Thing's 10 items now.
There we go: ['Apples', 'Oranges', 'Crows', 'Telephone', 'Light', 'Sugar', 'Boy', 'Girl', 'Banana', 'Corn']
Let's do some things with stuff.
Oranges
Corn
Corn
Apples Oranges Crows Telephone Light Sugar Boy Girl Banana
Telephone#Light
Python 相关文章推荐
python实现进程间通信简单实例
Jul 23 Python
python简单分割文件的方法
Jul 30 Python
Python的GUI框架PySide的安装配置教程
Feb 16 Python
Python操作mysql数据库实现增删查改功能的方法
Jan 15 Python
pandas对指定列进行填充的方法
Apr 11 Python
总结python中pass的作用
Feb 27 Python
Django实现微信小程序的登录验证功能并维护登录态
Jul 04 Python
python 中的9个实用技巧,助你提高开发效率
Aug 30 Python
python实现简单贪吃蛇游戏
Sep 29 Python
协程Python 中实现多任务耗资源最小的方式
Oct 19 Python
python基于win32api实现键盘输入
Dec 09 Python
还在手动盖楼抽奖?教你用Python实现自动评论盖楼抽奖(一)
Jun 07 Python
Python中的if、else、elif语句用法简明讲解
Mar 11 #Python
使用Python读写文本文件及编写简单的文本编辑器
Mar 11 #Python
简单讲解Python中的数字类型及基本的数学计算
Mar 11 #Python
详解Python中的变量及其命名和打印
Mar 11 #Python
Python基本语法经典教程
Mar 11 #Python
Python使用PIL库实现验证码图片的方法
Mar 11 #Python
Python2.x利用commands模块执行Linux shell命令
Mar 11 #Python
You might like
dede3.1分页文字采集过滤规则详说(图文教程)续二
2007/04/03 PHP
php md5下16位和32位的实现代码
2008/04/09 PHP
PHP分页显示制作详细讲解
2008/11/19 PHP
PHP实现将HTML5中Canvas图像保存到服务器的方法
2014/11/28 PHP
php检查字符串中是否有外链的方法
2015/07/29 PHP
PHPCMS V9 添加二级导航的思路详解
2016/10/20 PHP
Yii2使用表单上传文件的实例代码
2017/08/03 PHP
PHP重置数组为连续数字索引的几种方式总结
2018/03/12 PHP
php闭包中使用use声明变量的作用域实例分析
2018/08/09 PHP
python进程与线程小结实例分析
2018/11/11 PHP
PHP设计模式之建造者模式(Builder)原理与用法案例详解
2019/12/12 PHP
浅谈jQuery before和insertBefore的区别
2016/12/04 Javascript
基于JavaScript实现百度搜索框效果
2020/06/28 Javascript
解决vue.js在编写过程中出现空格不规范报错的问题
2017/09/20 Javascript
使用Angular CLI从蓝本生成代码详解
2018/03/24 Javascript
详解在Angular4中使用ng2-baidu-map的方法
2019/06/19 Javascript
Js逆向实现滑动验证码图片还原的示例代码
2020/03/10 Javascript
vue自定义组件(通过Vue.use()来使用)即install的用法说明
2020/08/11 Javascript
python求质数的3种方法
2018/09/28 Python
使用python动态生成波形曲线的实现
2019/12/04 Python
浅谈图像处理中掩膜(mask)的意义
2020/02/19 Python
浅谈cv2.imread()和keras.preprocessing中的image.load_img()区别
2020/06/12 Python
python文件排序的方法总结
2020/09/13 Python
python将下载到本地m3u8视频合成MP4的代码详解
2020/11/24 Python
python使用scapy模块实现ARP扫描的过程
2021/01/21 Python
css3 利用transform打造走动的2D时钟
2020/10/20 HTML / CSS
阿联酋网上花店:Ferns N Petals
2018/02/14 全球购物
德国购买门票网站:ADticket.de
2019/10/31 全球购物
国外软件测试工程师面试题
2016/12/09 面试题
2014高中生入党思想汇报范文
2014/09/13 职场文书
维稳工作承诺书
2015/01/20 职场文书
Python音乐爬虫完美绕过反爬
2021/08/30 Python
分享MySQL常用 内核 Debug 几种常见方法
2022/03/17 MySQL
基于Python实现将列表数据生成折线图
2022/03/23 Python
python运算符之与用户交互
2022/04/13 Python
win11开机发生死循环重启怎么办?win11开机发生死循环重启解决方法
2022/08/05 数码科技