Chapter02 列表和元组

python包含6种内建的序列,这里学习常用的两种:列表和元组
列表可以修改,而元组不能。


序列概览
>>> edward = ['Edward Gumby', 52]
>>> john = ['Jihn Smith', 65]
>>> database = [edward,john]
>>> database
[['Edward Gumby', 52], ['Jihn Smith', 65]]
>>> 

通用序列操作
1.索引(indexing); 2.分片(sliceing); 3.加(adding);4.乘(multiplying)
1.索引 (indexing)
访问某个元素
>>> greeting = 'Hello'
>>> greeting[3]
'l'
>>> 
>>> greeting[-1]
'o'
>>> 

#根据给定的年月日以数字形式打印出日期

#!/usr/bin/env python
# -*- coding: utf-8 -*-
months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
]


# 以1-31的数字作为结尾的列表
endings = ['st', 'nd', 'rd'] + 17 * ['th'] \
+ ['st', 'nd', 'rd'] + 7 * ['th']  \
+ ['st']


year  = raw_input('Year: ')
month = raw_input('Month: ')
day   = raw_input('Day: ')


month_number = int(month)
day_number = int(day)


month_name = months[month_number-1]
ordinal = day + endings[day_number-1]


print month_name + ' ' + ordinal + ', ' + year
raw_input("Press <enter>")

Year: 1974
Month: (1-12): 8
Day(1-31): 16
August 16th, 1974

2.分片 (sliceing)
访问某范围元素
>>> numbers = [0,1,2,3,4,5,6,7,8,9]
>>> numbers[3:6]
[3, 4, 5]
>>> numbers[-3,-1]      # 中间应该是:而不是,
Traceback (most recent call last):
 File "<pyshell#17>", line 1, in <module>
numbers[-3,-1]
TypeError: list indices must be integers, not tuple
>>> numbers[-3:-1]
[7, 8]
>>> numbers[-3:]
[7, 8, 9]
>>> numbers[:3]
[0, 1, 2]
>>> numbers[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> 
可以有更大的步长,默认1
>>> numbers[0:10:1]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numbers[0:10:2]
[0, 2, 4, 6, 8]
>>> numbers[::4]
[0, 4, 8]
>>> numbers[8:3:-1]
[8, 7, 6, 5, 4]
>>> numbers[0:10:-2]            #步长方向应该和范围的方向相同
[]
>>> numbers[::-2]
[9, 7, 5, 3, 1]
>>> numbers[5::-2]
[5, 3, 1]
>>> numbers[:5:-2]
[9, 7]
>>> 

3.序列相加 (adding)
>>> [1,2,3] + [4,5,6]
[1, 2, 3, 4, 5, 6]
>>> 'Hello' + 'world'
'Helloworld'
>>> [1,2,3] + 'wod'


Traceback (most recent call last):
 File "<pyshell#36>", line 1, in <module>
[1,2,3] + 'wod'
TypeError: can only concatenate list (not "str") to list
>>> 'Hello' + "world"
'Helloworld'              #由此可已看出单双引号影响不大
>>> 

4.乘法 (multiplying)
>>> [42]*10
[42, 42, 42, 42, 42, 42, 42, 42, 42, 42]
>>> 'pythn '*5
'pythn pythn pythn pythn pythn '
>>> 

可以使用内建的值None来声明空列表
>>> sequence = [None] * 10
>>> sequence
[None, None, None, None, None, None, None, None, None, None]
>>> 

成员资格
in
>>> permission = 'rw'
>>> 'w' in permission
True
>>> 'f' in permission
False
>>> 

长度、最大小值
>>> len(numbers)
3
>>> max(numbers)
654
>>> min(numbers)
32
>>> 



list函数
>>> list('Hello')
['H', 'e', 'l', 'l', 'o']
>>> names = ['Alice', 'Ben', 'Cend', 'Dee', 'Earl']
>>> names
['Alice', 'Ben', 'Cend', 'Dee', 'Earl']

删除元素
>>> del names[2]
>>> names
['Alice', 'Ben', 'Dee', 'Earl

分片赋值
>>> names[2:] = list('wo')
>>> names
['Alice', 'Ben', 'w', 'o']

列表方法
>>> lst = [[1,2],1,1,[2,1,[1,2]]]
>>> lst
[[1, 2], 1, 1, [2, 1, [1, 2]]]
>>> lst.append(4) #添加元素
>>> lst
[[1, 2], 1, 1, [2, 1, [1, 2]], 4]
>>> lst.count(1) #计数
2
>>> lst.count([1,2])
1
>>> num = [5,6,7]
>>> lst.extend(num) #追加元素
>>> lst
[[1, 2], 1, 1, [2, 1, [1, 2]], 4, 5, 6, 7]
>>> lst.index(1) #计算第一个出现下标
1
>>> lst.index(7)
7
>>> lst.index(9)
Traceback (most recent call last):
 File "<pyshell#12>", line 1, in <module>
lst.index(9)
ValueError: 9 is not in list
>>> lst.insert(2,'what') #插入元素
>>> lst
[[1, 2], 1, 'what', 1, [2, 1, [1, 2]], 4, 5, 6, 7]
>>> lst.pop() #移除最后一个元素,并且返回值
7
>>> lst
[[1, 2], 1, 'what', 1, [2, 1, [1, 2]], 4, 5, 6]
>>> lst.remove(1) #移除第一个匹配项
>>> lst
[[1, 2], 'what', 1, [2, 1, [1, 2]], 4, 5, 6]
>>> lst.reverse() #反向存放
>>> lst
[6, 5, 4, [2, 1, [1, 2]], 1, 'what', [1, 2]]
>>> lst.sort() #排序,不返回任何值
>>> lst
[1, 4, 5, 6, [1, 2], [2, 1, [1, 2]], 'what']
>>> y = lst.sort() #这是错误的做法,因为sort不返回值
>>> y
>>> print y
Traceback (most recent call last):
 File "<pyshell#33>", line 1, in <module>
print t
NameError: name 't' is not defined
>>> print y
None

这里只是复制了数据,cop是副本,不影响原来的值
>>> numbers = [3,6,4,8,1,9,4]
>>> cop = numbers
>>> cop = numbers[:]
>>> cop.sort()
>>> cop
[1, 3, 4, 4, 6, 8, 9]
>>> numbers
[3, 6, 4, 8, 1, 9, 4]
同样可以使用sorted()来对副本y排序
>>> y = sorted(numbers)
>>> y
[1, 3, 4, 4, 6, 8, 9]
>>> numbers
[3, 6, 4, 8, 1, 9, 4]

这里的yoo和numbers指向同一个列表,所以操作同一个列表,互相影响
>>> yoo = numbers
>>> yoo.sort()
>>> yoo
[1, 3, 4, 4, 6, 8, 9]
>>> numbers
[1, 3, 4, 4, 6, 8, 9]

高级排序
>>> cmp(43,23)
1
>>> cmp(99,100)
-1
>>> cmp(1,1)
0

默认升序
>>> numbers.sort()
>>> numbers
[2, 5, 7, 9]
定义我的比较函数,使之反向排序,降序
>>> def my_cmp(a,b):
return -cmp(a,b)
>>> numbers.sort(my_cmp)
>>> numbers
[9, 7, 5, 2]

或者利用sort()的参数reverse
>>> numbers.sort(reverse = True)
>>> numbers
[9, 7, 5, 2]
另一个参数key
>>> x = ['asdg', 'basdg', 'cghr', 'dgyre', 'adgr', 'ahre']
>>> x.sort(key = len)
>>> x
['asdg', 'cghr', 'adgr', 'ahre', 'basdg', 'dgyre']




元组:不可变序列
创建
直接用‘,’隔开就可以
>>> 1,2,3
(1, 2, 3)
>>> (1,2,3)
(1, 2, 3)
空元组
>>> ()
()
包括一个值的元组
>>> 52
52
>>> 52,                   #必须后面跟着一个‘,’才可以
(52,)
>>> (52,)
(52,)
逗号能彻底地改变表达式的值
>>> 3 * (52+2)
162
>>> 3 * (52,+2)
(52, 2, 52, 2, 52, 2)
>>> 3 * (52+2,)
(54, 54, 54)


tuple函数
与list函数基本是一样的:以一个序列作为参数并把它转换为元组
>>> tuple([1,2,3])
(1, 2, 3)
>>> tuple('abc')
('a', 'b', 'c')

基本元组操作
除了创建元组和访问元组元素之外,没有太多其他操作
>>> x = 1,2,3
>>> x[1]
2
>>> x[0:2]
(1, 2)
>>> 




小结:
1.序列 list
2.元组 tuple
3.成员资格  in
4.一些方法  methods
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

信知阁

您的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值