Python列表脚本操作符
列表对 + 和 * 的操作符与字符串相似。+ 号用于组合列表,* 号用于重复列表。
如下所示:
Python 表达式 |
结果 |
描述 |
len([1, 2, 3]) |
3 |
长度 |
[1, 2, 3] + [4, 5, 6] |
[1, 2, 3, 4, 5, 6] |
组合 |
['Hi!'] * 4 |
['Hi!', 'Hi!', 'Hi!', 'Hi!'] |
重复 |
3 in [1, 2, 3] |
True |
元素是否存在于列表中 |
for x in [1, 2, 3]: print x, |
1 2 3 |
迭代 |
Python列表截取
Python的列表截取与字符串操作类型,如下所示:
L = ['spam', 'Spam', 'SPAM!']
操作:
Python 表达式 |
结果 |
描述 |
L[2] |
'SPAM!' |
读取列表中第三个元素 |
L[-2] |
'Spam' |
读取列表中倒数第二个元素 |
L[1:] |
['Spam', 'SPAM!'] |
从第二个元素开始截取列表 |
Python列表函数&方法
Python包含以下函数:
序号 |
函数 |
1 |
cmp(list1, list2) 比较两个列表的元素 |
2 |
len(list) 列表元素个数 |
3 |
max(list) 返回列表元素最大值 |
4 |
min(list) 返回列表元素最小值 |
5 |
list(seq) 将元组转换为列表 |
Python包含以下方法:
序号 |
方法 |
1 |
list.append(obj) 在列表末尾添加新的对象 |
2 |
list.count(obj) 统计某个元素在列表中出现的次数 |
3 |
list.extend(seq) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表) |
4 |
list.index(obj) 从列表中找出某个值第一个匹配项的索引位置 |
5 |
list.insert(index, obj) 将对象插入列表 |
6 |
list.pop(obj=list[-1]) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 |
7 |
list.remove(obj) 移除列表中某个值的第一个匹配项 |
8 |
list.reverse() 反向列表中元素 |
9 |
list.sort([func]) 对原列表进行排序 |
Python 字典(Dictionary)
字典是另一种可变容器模型,且可存储任意类型对象,如其他容器模型。
字典由键和对应值成对组成。字典也被称作关联数组或哈希表。基本语法如下:
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
也可如此创建字典:
dict1 = { 'abc': 456 };
dict2 = { 'abc': 123, 98.6: 37 };
每个键与值用冒号隔开(:),每对用逗号,每对用逗号分割,整体放在花括号中({})。
键必须独一无二,但值则不必。
访问字典里的值
把相应的键放入熟悉的方括弧,如下实例:
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print "dict['Name']: ", dict['Name'];
print "dict['Age']: ", dict['Age'];
以上实例输出结果:
dict['Name']: Zara
dict['Age']: 7
如果用字典里没有的键访问数据,会输出错误如下:
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print "dict['Alice']: ", dict['Alice'];
以上实例输出结果:
dict['Zara']:
Traceback (most recent call last):
File "test.py", line 4, in
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'
修改字典
向字典添加新内容的方法是增加新的键/值对,修改或删除已有键/值对如下实例:
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];
以上实例输出结果:
dict['Age']: 8
dict['School']: DPS School
删除字典元素
能删单一的元素也能清空字典,清空只需一项操作。
显示删除一个字典用del命令,如下实例:
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
del dict['Name']; # 删除键是'Name'的条目
dict.clear(); # 清空词典所有条目
del dict ; # 删除词典
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];
但这会引发一个异常,因为用del后字典不再存在:
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
注:del()方法后面也会讨论。
删除字典元素
字典键的特性
字典值可以没有限制地取任何python对象,既可以是标准的对象,也可以是用户定义的,但键不行。
两个重要的点需要记住:
1)不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住,如下实例:
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'};
print "dict['Name']: ", dict['Name'];
以上实例输出结果:
dict['Name']: Manni
2)键必须不可变,所以可以用数,字符串或元组充当,所以用列表就不行,如下实例:
#!/usr/bin/python
dict = {['Name']: 'Zara', 'Age': 7};
print "dict['Name']: ", dict['Name'];
以上实例输出结果:
Traceback (most recent call last):
File "test.py", line 3, in
dict = {['Name']: 'Zara', 'Age': 7};
TypeError: list objects are unhashable
字典内置函数&方法
Python字典包含了以下内置函数:
序号 |
函数及描述 |
1 |
cmp(dict1, dict2) 比较两个字典元素。 |
2 |
len(dict) 计算字典元素个数,即键的总数。 |
3 |
str(dict) 输出字典可打印的字符串表示。 |
4 |
type(variable) 返回输入的变量类型,如果变量是字典就返回字典类型。 |
Python字典包含了以下内置函数:
序号 |
函数及描述 |
1 |
radiansdict.clear() 删除字典内所有元素 |
2 |
radiansdict.copy() 返回一个字典的浅复制 |
3 |
radiansdict.fromkeys() 创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值 |
4 |
radiansdict.get(key, default=None) 返回指定键的值,如果值不在字典中返回default值 |
5 |
radiansdict.has_key(key) 如果键在字典dict里返回true,否则返回false |
6 |
radiansdict.items() 以列表返回可遍历的(键, 值) 元组数组 |
7 |
radiansdict.keys() 以列表返回一个字典所有的键 |
8 |
radiansdict.setdefault(key, default=None) 和get()类似, 但如果键不已经存在于字典中,将会添加键并将值设为default |
9 |
radiansdict.update(dict2) 把字典dict2的键/值对更新到dict里 |
10 |
radiansdict.values() 以列表返回字典中的所有值 |
Python 日期和时间
Python程序能用很多方式处理日期和时间。转换日期格式是一个常见的例行琐事。Python有一个time and calendar模组可以帮忙。
什么是Tick?
时间间隔是以秒为单位的浮点小数。
每个时间戳都以自从1970年1月1日午夜(历元)经过了多长时间来表示。
Python附带的受欢迎的time模块下有很多函数可以转换常见日期格式。如函数time.time()用ticks计时单位返回从12:00am, January 1, 1970(epoch) 开始的记录的当前操作系统时间, 如下实例:
#!/usr/bin/python
import time; # This is required to include time module.
ticks = time.time()
print "Number of ticks since 12:00am, January 1, 1970:", ticks
以上实例输出结果:
Number of ticks since 12:00am, January 1, 1970: 7186862.73399
Tick单位最适于做日期运算。但是1970年之前的日期就无法以此表示了。太遥远的日期也不行,UNIX和Windows只支持到2038年某日。
什么是时间元组?
很多Python函数用一个元组装起来的9组数字处理时间:
序号 |
字段 |
值 |
0 |
4位数年 |
2008 |
1 |
月 |
1 到 12 |
2 |
日 |
1到31 |
3 |
小时 |
0到23 |
4 |
分钟 |
5 |
秒 |
0到61 (60或61 是闰秒) |
6 |
一周的第几日 |
0到6 (0是周一) |
7 |
一年的第几日 |
1到366 (儒略历) |
8 |
夏令时 |
-1, 0, 1, -1是决定是否为夏令时的旗帜 |
上述也就是struct_time元组。这种结构具有如下属性:
序号 |
属性 |
值 |
0 |
tm_year |
2008 |
1 |
tm_mon |
1 到 12 |
2 |
tm_mday |
1 到 31 |
3 |
tm_hour |
0 到 23 |
4 |
tm_min |
0 到 59 |
5 |
tm_sec |
0 到 61 (60或61 是闰秒) |
6 |
tm_wday |
0到6 (0是周一) |
7 |
tm_yday |
1 到 366(儒略历) |
8 |
tm_isdst |
-1, 0, 1, -1是决定是否为夏令时的旗帜 |
获取当前时间
从返回浮点数的时间辍方式向时间元组转换,只要将浮点数传递给如localtime之类的函数。
#!/usr/bin/python
import time;
localtime = time.localtime(time.time())
print "Local current time :", localtime
以上实例输出结果:
Local current time : time.struct_time(tm_year=2013, tm_mon=7,
tm_mday=17, tm_hour=21, tm_min=26, tm_sec=3, tm_wday=2, tm_yday=198, tm_isdst=0)
获取格式化的时间
你可以根据需求选取各种格式,但是最简单的获取可读的时间模式的函数是asctime():
#!/usr/bin/python
import time;
localtime = time.asctime( time.localtime(time.time()) )
print "Local current time :", localtime
以上实例输出结果:
Local current time : Tue Jan 13 10:17:09 2009
获取某月日历
Calendar模块有很广泛的方法用来处理年历和月历,例如打印某月的月历:
#!/usr/bin/python
import calendar
cal = calendar.month(2008, 1)
print "Here is the calendar:"
print cal;
以上实例输出结果:
Here is the calendar:
January 2008
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Time模块
Time模块包含了以下内置函数,既有时间处理相的,也有转换时间格式的:
序号 |
函数及描述 |
1 |
time.altzone 返回格林威治西部的夏令时地区的偏移秒数。如果该地区在格林威治东部会返回负值(如西欧,包括英国)。对夏令时启用地区才能使用。 |
2 |
time.asctime([tupletime]) 接受时间元组并返回一个可读的形式为"Tue Dec 11 18:07:14 2008"(2008年12月11日 周二18时07分14秒)的24个字符的字符串。 |
3 |
time.clock( ) 用以浮点数计算的秒数返回当前的CPU时间。用来衡量不同程序的耗时,比time.time()更有用。 |
4 |
time.ctime([secs]) 作用相当于asctime(localtime(secs)),未给参数相当于asctime() |
5 |
time.gmtime([secs]) 接收时间辍(1970纪元后经过的浮点秒数)并返回格林威治天文时间下的时间元组t。注:t.tm_isdst始终为0 |
6 |
time.localtime([secs]) 接收时间辍(1970纪元后经过的浮点秒数)并返回当地时间下的时间元组t(t.tm_isdst可取0或1,取决于当地当时是不是夏令时)。 |
7 |
time.mktime(tupletime) 接受时间元组并返回时间辍(1970纪元后经过的浮点秒数)。 |
8 |
time.sleep(secs) 推迟调用线程的运行,secs指秒数。 |
9 |
time.strftime(fmt[,tupletime]) 接收以时间元组,并返回以可读字符串表示的当地时间,格式由fmt决定。 |
10 |
time.strptime(str,fmt='%a %b %d %H:%M:%S %Y') 根据fmt的格式把一个时间字符串解析为时间元组。 |
11 |
time.time( ) 返回当前时间的时间戳(1970纪元后经过的浮点秒数)。 |
12 |
time.tzset() 根据环境变量TZ重新初始化时间相关设置。 |
Time模块包含了以下2个非常重要的属性:
序号 |
属性及描述 |
1 |
time.timezone 属性time.timezone是当地时区(未启动夏令时)距离格林威治的偏移秒数(>0,美洲;<=0大部分欧洲,亚洲,非洲)。 |
2 |
time.tzname 属性time.tzname包含一对根据情况的不同而不同的字符串,分别是带夏令时的本地时区名称,和不带的。 |
日历(Calendar)模块
此模块的函数都是日历相关的,例如打印某月的字符月历。
星期一是默认的每周第一天,星期天是默认的最后一天。更改设置需调用calendar.setfirstweekday()函数。模块包含了以下内置函数:
序号 |
函数及描述 |
1 |
calendar.calendar(year,w=2,l=1,c=6) 返回一个多行字符串格式的year年年历,3个月一行,间隔距离为c。 每日宽度间隔为w字符。每行长度为21* W+18+2* C。l是每星期行数。 |
2 |
calendar.firstweekday( ) 返回当前每周起始日期的设置。默认情况下,首次载入caendar模块时返回0,即星期一。 |
3 |
calendar.isleap(year) 是闰年返回True,否则为false。 |
4 |
calendar.leapdays(y1,y2) 返回在Y1,Y2两年之间的闰年总数。 |
5 |
calendar.month(year,month,w=2,l=1) 返回一个多行字符串格式的year年month月日历,两行标题,一周一行。每日宽度间隔为w字符。每行的长度为7* w+6。l是每星期的行数。 |
6 |
calendar.monthcalendar(year,month) 返回一个整数的单层嵌套列表。每个子列表装载代表一个星期的整数。Year年month月外的日期都设为0;范围内的日子都由该月第几日表示,从1开始。 |
7 |
calendar.monthrange(year,month) 返回两个整数。第一个是该月的星期几的日期码,第二个是该月的日期码。日从0(星期一)到6(星期日);月从1到12。 |
8 |
calendar.prcal(year,w=2,l=1,c=6) 相当于 print calendar.calendar(year,w,l,c). |
9 |
calendar.prmonth(year,month,w=2,l=1) 相当于 print calendar.calendar(year,w,l,c)。 |
10 |
calendar.setfirstweekday(weekday) 设置每周的起始日期码。0(星期一)到6(星期日)。 |
11 |
calendar.timegm(tupletime) 和time.gmtime相反:接受一个时间元组形式,返回该时刻的时间辍(1970纪元后经过的浮点秒数)。 |
12 |
calendar.weekday(year,month,day) 返回给定日期的日期码。0(星期一)到6(星期日)。月份为 1(一月) 到 12(12月)。 |
其他相关模块和函数
在Python种,其他处理日期和时间的模块还有:
- datetime模块
- pytz模块
- ateutil模块