Python序列——列表
1. 列表是什么
列表也是序列的一种。列表能保存任意数目的Python对象,列表是可变类型。
1.1 创建列表
列表可以使用[]来创建,或者使用工厂方法list()来创建。
>>> t = list()
>>> type(t)
<type 'list'>
>>> l = []
>>> type(l)
<type 'list'>
>>> t == l
True
1.2 访问列表和更新列表
>>> t = list('furzoom')
>>> t
['f', 'u', 'r', 'z', 'o', 'o', 'm']
>>> t[1]
'u'
>>> t[2] = 'n'
>>> t
['f', 'u', 'n', 'z', 'o', 'o', 'm']
>>> t.append('.')
>>> t
['f', 'u', 'n', 'z', 'o', 'o', 'm', '.']
>>> del t[3]
>>> t
['f', 'u', 'n', 'o', 'o', 'm', '.']
>>> del t
>>> t
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 't' is not defined
2. 列表相关操作
支持比较运算、切片[]或者[:]、in, not in、连接操作符+、重复操作。
如果可以,尽量使用list.extend()方式代替连接操作符。
列表还支持非常重要的列表解析操作。
>>> [i for i in xrange(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3. 内建函数对列表的支持
3.1 cmp()
比较原则:
- 对两个列表的元素进行比较。
- 如果比较的元素是同类型的,则比较其值,返回结果。
- 如果两个元素不是同一类型的,则检查它们是否是数字。
3.1 如果是数字,执行必要的数字强制类型转换,然后比较。
3.2 如果有一方的元素是数字,则另一方的元素大。
3.3 否则,通过类型名字的字母顺序进行比较。 - 如果有一个列表首先到达末尾,则另一个长一点的列表大。
- 如果两个列表都到达结尾,且所有元素都相等,则返回0。
3.2 序列类型函数
- len()
- max()
- min()
- sorted()
- reversed()
- enumerate()
- zip()
- sum()
- list()
- tuple()
4. 列表内建函数
- list.append(x)
- list.extend(x)
- list.count(x)
- list.index(x[, start[, end]])
- list.insert(index, x)
- list.pop([index])
- list.remove(x)
- list.remove()
- list.sort([cmp[, key[, reverse]]])
5. 列表应用
5.1 堆栈
#!/usr/bin/env python
# -*- coding: utf-8 -*-
stack = []
def pushit():
stack.append(raw_input('Enter New string: ').strip())
def popit():
if len(stack) == 0:
print 'Cannot pop from an empty stack!'
else:
print 'Removed [', `stack.pop()`, ']'
def viewstack():
print stack
CMDs = {'u': pushit, 'o': popit, 'v': viewstack}
def showmenu():
pr = """
p(U)sh
p(O)p
(V)iew
(Q)uit
Enter choice: """
while True:
while True:
try:
choice = raw_input(pr).strip()[0].lower()
except (EOFError, KeyboardInterrupt, IndexError):
choice = 'q'
print '\nYou picked: [%s]' % choice
if choice not in 'uovq':
print 'Invalid option, try again'
else:
break
if choice == 'q':
break
CMDs[choice]()
if __name__ == '__main__':
showmenu()
运行示例如下:
p(U)sh
p(O)p
(V)iew
(Q)uit
Enter choice: u
You picked: [u]
Enter New string: Python
p(U)sh
p(O)p
(V)iew
(Q)uit
Enter choice: u
You picked: [u]
Enter New string: is
p(U)sh
p(O)p
(V)iew
(Q)uit
Enter choice: u
You picked: [u]
Enter New string: cool!
p(U)sh
p(O)p
(V)iew
(Q)uit
Enter choice: v
You picked: [v]
['Python', 'is', 'cool!']
p(U)sh
p(O)p
(V)iew
(Q)uit
Enter choice: o
You picked: [o]
Removed [ 'cool!' ]
p(U)sh
p(O)p
(V)iew
(Q)uit
Enter choice: o
You picked: [o]
Removed [ 'is' ]
p(U)sh
p(O)p
(V)iew
(Q)uit
Enter choice: o
You picked: [o]
Removed [ 'Python' ]
p(U)sh
p(O)p
(V)iew
(Q)uit
Enter choice: o
You picked: [o]
Cannot pop from an empty stack!
p(U)sh
p(O)p
(V)iew
(Q)uit
Enter choice: ^D
You picked: [q]
5.2 队列
#!/usr/bin/env python
# -*- coding: utf-8 -*-
queue = []
def enQ():
queue.append(raw_input('Enter New string: ').strip())
def deQ():
if len(queue) == 0:
print 'Cannot pop from an empty queue!'
else:
print 'Removed [', `queue.pop(0)`, ']'
def viewQ():
print queue
CMDs = {'e': enQ, 'd': deQ, 'v': viewQ}
def showmenu():
pr = """
(E)nqueue
(D)equeue
(V)iew
(Q)uit
Enter choice: """
while True:
while True:
try:
choice = raw_input(pr).strip()[0].lower()
except (EOFError, KeyboardInterrupt, IndexError):
choice = 'q'
print '\nYou picked: [%s]' % choice
if choice not in 'edvq':
print 'Invalid option, try again'
else:
break
if choice == 'q':
break
CMDs[choice]()
if __name__ == '__main__':
showmenu()
运行示例如下:
(E)nqueue
(D)equeue
(V)iew
(Q)uit
Enter choice: e
You picked: [e]
Enter New string: Bring out
(E)nqueue
(D)equeue
(V)iew
(Q)uit
Enter choice: e
You picked: [e]
Enter New string: your dead!
(E)nqueue
(D)equeue
(V)iew
(Q)uit
Enter choice: v
You picked: [v]
['Bring out', 'your dead!']
(E)nqueue
(D)equeue
(V)iew
(Q)uit
Enter choice: d
You picked: [d]
Removed [ 'Bring out' ]
(E)nqueue
(D)equeue
(V)iew
(Q)uit
Enter choice: d
You picked: [d]
Removed [ 'your dead!' ]
(E)nqueue
(D)equeue
(V)iew
(Q)uit
Enter choice: d
You picked: [d]
Cannot pop from an empty queue!
(E)nqueue
(D)equeue
(V)iew
(Q)uit
Enter choice: ^D
You picked: [q]
Python序列——列表的更多相关文章
- python序列(列表,元组,字典)的常用排序
列表 正向排序 sort() >>> list=[1,6,3,4,5,2] >>> list.sort() >>> list [1, 2, 3, ...
- python序列(列表,元组,字典)的增删改查
列表 操作 列表 方法 示例 增加 list.append(obj) 增加元素到末尾 eg. >>> list1=['hello','world','how','are','you' ...
- python 序列:字符串、列表、元组
python 序列:字符串.列表.元组 序列:包含一定顺序排列的对象的一个结构 内建函数:str() list() tuple() 可以使用str(obj)可以把对象obj转换成字符串 list( ...
- Python数据类型-03.序列-列表和元组
本文主要记录关于Python序列中列表和元组的定义特点和常用方法 1.序列(sequence) 1.1.序列的定义 序列是一组有顺序的元素的集合(其实是是对象的集合,后期会引入“对象”这个概念)序列包 ...
- Python序列之列表(一)
在Python中,列表是一种常用的序列,接下来我来讲一下关于Python中列表的知识. 列表的创建 Python中有多种创建列表的方式 1.使用赋值运算符直接赋值创建列表 在创建列表时,我们直接使用赋 ...
- Python语言之数据结构1(序列--列表,元组,字符串)
0.序列 列表,元组,字符串都是序列. 序列有两个特点:索引操作符和切片操作符.索引操作符让我们可以从序列中抓取一个特定项目.切片操作符让我们能够获取序列的一个切片,即一部分序列. 以字符串为例: 1 ...
- [Python笔记][第二章Python序列-复杂的数据结构]
2016/1/27学习内容 第二章 Python序列-复杂的数据结构 堆 import heapq #添加元素进堆 heapq.heappush(heap,n) #小根堆堆顶 heapq.heappo ...
- [Python笔记][第二章Python序列-tuple,dict,set]
2016/1/27学习内容 第二章 Python序列-tuple tuple创建的tips a_tuple=('a',),要这样创建,而不是a_tuple=('a'),后者是一个创建了一个字符 tup ...
- [python笔记][第二章Python序列-list]
2016/1/27学习内容 第二章 Python序列-list list常用操作 list.append(x) list.extend(L) list.insert(index,x) list.rem ...
随机推荐
- vue v-show与v-for同时配合v-bind使用并在href中传递多个参数的使用方法
最近在项目中,因为还没使用前端构建工具,还在使用vue+jquery方法渲染页面 碰到几个小问题,在此记录下作为vue学习之路上的一个小知识点 需求:1.数据列表存在与否状态,没有数据显示默认提示,有 ...
- codeforces A. Wrong Subtraction
A. Wrong Subtraction time limit per test 1 second memory limit per test 256 megabytes input standard ...
- Ubuntu 16.04安装Wine版的迅雷+QQ(完美方案,终极解决方法)
安装前先备份好系统! 继上一篇安装QQ的方法http://www.cnblogs.com/EasonJim/p/7425978.html,这一篇的QQ采用的是Wine模式安装.完美解决消息记录中文乱码 ...
- SQL SERVER 内存
http://www.cnblogs.com/CareySon/archive/2012/08/16/HowSQLServerManageMemory.html
- Android Studio 删除项目
在项目上右键 点击“Open Module Settings”,然后你会看到你的项目排成一列,如果想删除哪个,点击项目,然后在左上角,点击“-”号,然后返回后发现这个项目变为灰色,点击项目右键,看到“ ...
- 【java】深入分析Java ClassLoader原理
一.什么是ClassLoader? 大家都知道,当我们写好一个Java程序之后,不是管是CS还是BS应用,都是由若干个.class文件组织而成的一个完整的Java应用程序,当程序在运行时,即会调用该程 ...
- Ubuntu中一次更改用户名带来的连锁反应
我是一个ubuntu新手,接触ubuntu半年不到,装系统的时候输入了一个用户名,但是最近突然想更名了,这是悲剧的开始! google:ubuntu change username等相关的关键字,最终 ...
- 金山面试CDN
History 今天去金山网络面试的时候,被问到性能优化,我说了几个.最后说到了CDN,我说要尽量把静态的内容放置到CDN,可是为什么呢?面试官说既然你说到CDN.你就说说它的原理. 之前有看过,可是 ...
- C++11中的原子操作(atomic operation)(转)
所谓的原子操作,取的就是“原子是最小的.不可分割的最小个体”的意义,它表示在多个线程访问同一个全局资源的时候,能够确保所有其他的线程都不在同一时间内访问相同的资源.也就是他确保了在同一时刻只有唯一的线 ...
- linux遍历目录源代码
<pre code_snippet_id="1622396" snippet_file_name="blog_20160324_1_744516" nam ...