Python数据结构:序列——元组和列表

来源:互联网 发布:python中readline 编辑:程序博客网 时间:2024/06/10 01:48

序列(sequence)是容器(container)

序列的一个重要特性:每个元素都有位置/索引——跟字典很大的不同。


元组

Tuples are immutable(=String), that means you can't do with tuples like this:

tuple.sort()tuple.append(5)tuple.reverse() 

这些都是自带的方法(像 object.function这种形式的使用方法),将会实际的改变自身。

逗号, 是tuple 的标志:

x = 4,5,6print xprint 3*(40+2),3*(40+2,)

Tuple 的最大用途就是充当临时的、长度固定的变量(就如同希望字典里面的值按照 value 而不是 key 进行排序):

假设有一个 dict:{'csev': 2, 'zqian': 1, 'cwen': 4}

temp = list()for k,v in dict.items():    temp.append( (v,k) ) # notice there is a tuple temp.sort(reverse = True )print temp

这样就可以达到找到最大值的目的(统计出现频率最高的几个数)

tuples不仅仅可以包含constant,如下代码:
a = 1b = 99.0c = 'hello'tuple0 = (a, b, c, 1)print tuple0

tuples 还可以包含变量,变量以及constant 的组合,其中tuple0本身也就是一个变量。


列表

List are mutable,所有可以对序列做的同样适用于列表。

给出一个 list 供后续操作:

list0 = [1, 2, 'joe', 99.0]

1. 列表和字符串相互转化:

lst = list('hello')print lst, ''.join(lst)

2. 改变列表——需要指定列表下标

元素赋值:

list0 = [1, 2, 'joe', 99.0]list0[1] = 3print list0list0[99] = 'error' # index out of range
删除特定位置元素:

list0 = [1, 2, 'joe', 99.0]del list0[1]print list0
选择性赋值——分片

#change valuename = list('Perl')name[2:] = list('ar')print name# change list length and valuename[1:] = list('ython')print name# insertnumbers = [1,5]numbers[1:1] = [2,3,4]numbers[0:0] = [0]print numbers# deletenumbers[1:5] = []print numbers
分片的替换的值必须是列表

3. 末尾追加新对象(一个元素,注意后面的extend)append()

list0 = [1, 2, 'joe', 99.0]list0.append([1,2])print list0
直接改变原列表


4. 统计某个元素在列表中出现次数 count()

list0 = [1, 2, 'joe', 99.0]print list0.count('joe'),list0.count(1)

5. 在末尾追加多个值 extend()

list0 = [1, 2, 'joe', 99.0]b = [7,8,9]list0.extend(b)print list0
与 + 不同,这个extend 直接改变原列表

也可以用下列代码替换:

list0 = [1, 2, 'joe', 99.0]b = [7,8,9]#print len(list0),list0[4:]list0[ len(list0):] = b # attention is len(list0)print list0


7. 在任意位置插入对象insert()

list0 = [1, 2, 'joe', 99.0]list0.insert(2,'position:2')print list0
同理可以切片 insert 

6. 查找某个值第一个匹配项下标  index()

list0 = [1, 2, 'joe', 99.0]print list0.index('joe'),list0.index(99.0)print list0.index(5)


7. 移除一个元素,并获得该元素 pop(index)

list0 = [1, 2, 'joe', 99.0]list0.append( list0.pop() )print list0list0.pop(0)print list0
pop() 会返回移除的元素的值。


8. 移除第一个匹配项 remove(element)

list0 = [1, 2, 'joe', 99.0,'joe']list0.remove('joe')print list0

9. 反向存放 reverse()

list0 = [1, 2, 'joe', 99.0,'joe']list0.reverse()print list0

10. 对原列表排序 sort() 返回列表

<pre name="code" class="python">x = [57,9,8,7,85,4,4,3,5]y = sorted(x)print x,yy = x.sort()x.reverse() #反向排序x.sort(reverse = True) #反向排序print x,y

sorted() 是直接使用的,并没有使用对象.方法()这种方式。而所有的列表方法,会改变列表本身的方法基本上都使用了——对象.方法() 这种形式

再次提醒一下,需要注意函数的返回值——None。

所以,使用object.sort().reverse() 是无效的,而sorted(object).reverse() 因为返回值不为None,有效。

注意上列的函数都是会对原列表值直接进行改变,所以,如果要备份,可以使用切片赋值备份

y = list0[:]
直接赋值是会出错的,因为两个指向的是同一个地址,并没有进行备份


11. How long a list : len()

len(list0)

这将会显示出 list 中有多少个元素。

len() 可以用于 for 里的range() 函数,如下(在 Python 中这样做会十分的繁琐,不建议但是可以作为了解):

for i in range( len(list0) ):    print list0[i]


12. Calculation method: max(), mins(), sum()

numlist = list()while True:    inp = raw_input('Enter a number:')    if inp == 'done': break    value = float(inp)    numlist.append(value)    average = sum(numlist) / len(numlist)print 'Average', average

实际上这样计算平均会很简单易懂,但是将会浪费一些内存空间

当然,list 的操作还有很多


13. list 容易混淆的操作

list = [1,2,3]print list + [1]print list + 1print list - [1]
唯有第一个操作是正确的,list 没有 “-” 操作,list 也只能concatenate list

同上述tuple,列表不仅仅只是可以包含 constant ,如下代码:

a = 1b = 99.0c = 'hello'list1 = [a, b, c]print list1

列表同样可以包含变量、变量和constant 的组合,其中list1 本身也就是一个变量。

实际上,利用这一点,逆推可以得到——list / tuple 中的值也可以赋值给对应的变量(前提是 变量数目 == list / tuple 中的值的数目)称为“unpack”

List & Tuple 

特别提一下列表 & 元组的结合。

records = [     ('foo', 1),     ('bar', 'hello'),     ('foo', 3, 4),]for i in records: # just one iteration variable    print ifor i, j in records:# two iteration variable    print i, j
可以看到:

1.  1个循环变量和2个循环变量打印出来的结果是不相同的:参考上面所提到的 unpack—— 一个循环变量是以一个元组为单位,每一次循环就将每个列表中的元组 unpack 给变量 i ;当具有两个循环变量的时候,它的需求改变为需要 列表中的元组中的元素的 unpack 了,同如下代码:

list0 = [ 'ACME', 50, 91.1, (2012, 12, 21) ]a, b, c, d = list0print a, b, c, da, b, c, (i, j, k) = list0print a, b, c, i, j, klist1 = [ 'ACME', 50, 91.1, [2012, 12, 21] ]a, b, c, d = list1print a, b, c, da, b, c, [i, j, k] = list1print a, b, c, i, j, k

当然,在循环中,list / tuple 的一对括号是可以省略的。

2. 值得注意的是,records 里面存的tuple 的元素并非固定为两个,当运行到第三个 tuple 的时候,程序就会出错,那么怎么解决这样一个问题呢? 在Python3 当中可以使用 starred variable。那么Python2 当中应该怎么解决?



0 0