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

本文介绍了Python中的序列类型,重点讲解了元组和列表的特性。元组是不可变的,常用于临时存储固定长度的数据,而列表是可变的,支持多种操作如添加、删除元素。两者在处理字典数据、元素赋值、操作方法等方面有所不同,例如列表的sort()和reverse()会改变原列表,而sorted()不会。文章还讨论了列表和元组的混合使用,包括 unpacking 和使用starred variable解决元素数量不固定的问题。
摘要由CSDN通过智能技术生成

序列(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,6
print x
print 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 = 1
b = 99.0
c = '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] = 3
print list0
list0[99] = 'error' # index out of range
删除特定位置元素:

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

#change value
name = list('Perl')
name[2:] = list('ar')
print name
# change list length and value
name[1:] = list('ython')
print name
# insert
numbers = [1,5]
numbers[1:1] = [2,3,4]
numbers[0:0] = [0]
print numbers
# delete
numbers[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 list0
list0.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,y
y = 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 + 1
print list - [1]
唯有第一个操作是正确的,list 没有 “-” 操作,list 也只能concatenate list

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

a = 1
b = 99.0
c = '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 i

for 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 = list0
print a, b, c, d
a, b, c, (i, j, k) = list0
print a, b, c, i, j, k

list1 = [ 'ACME', 50, 91.1, [2012, 12, 21] ]
a, b, c, d = list1
print a, b, c, d
a, b, c, [i, j, k] = list1
print a, b, c, i, j, k

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

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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值