您的位置:首页 > 编程语言 > Python开发

python基础-OrderedDict、defaultdict、Counter、时间模块、sys模块

2017-11-14 20:25 603 查看
OrderedDict

defaultdict

Counter

time时间模块

sys模块模块

OrderedDict

如果要保持Key的顺序,可以用OrderedDict:

from collections import OrderedDict
od = OrderedDict([('a', [1,2,3,4]), ('b', 2), ('c', 3)])
for k in od:
print(k,od[k])

print("-----items----")
od = OrderedDict()
od["k1"] = "v1"
od["k2"] = "v2"
print(od)
print(od.items())
print(od.keys())
print(od.values())

print("-----fromkeys----")
od = OrderedDict()
name = ["a","b","c"]
od = od.fromkeys(name)
print(od)
od = od.fromkeys(name,20)
print(od)

print("----move_to_end(指定一个key,把对应的key-value移到最后)-")
od.move_to_end("a")
print(od)

print("---#pop(获取指定key的value,并在字典中删除))-")
od.pop("a")
print(od)

print("--popitem(按照后进先出原则,删除最后加入的元素,返回key-value)--")

od.popitem()
print(od)

print("--setdefault(获取指定key的value,如果key不存在,则创建)---")

od.setdefault("d")
print(od)

#字典也可以
print("-----dic----")
od = {}
print(od.fromkeys(name))

od = {"a":1,"b":2}
print(od)
print(od.items())


输出如下:

E:\python\python_sdk\python.exe E:/python/py_pro/4collections.py
a [1, 2, 3, 4]
b 2
c 3
-----items----
OrderedDict([('k1', 'v1'), ('k2', 'v2')])
odict_items([('k1', 'v1'), ('k2', 'v2')])
odict_keys(['k1', 'k2'])
odict_values(['v1', 'v2'])
-----fromkeys----
OrderedDict([('a', None), ('b', None), ('c', None)])
OrderedDict([('a', 20), ('b', 20), ('c', 20)])
----move_to_end(指定一个key,把对应的key-value移到最后)-
OrderedDict([('b', 20), ('c', 20), ('a', 20)])
---#pop(获取指定key的value,并在字典中删除))-
OrderedDict([('b', 20), ('c', 20)])
--popitem(按照后进先出原则,删除最后加入的元素,返回key-value)--
OrderedDict([('b', 20)])
--setdefault(获取指定key的value,如果key不存在,则创建)---
OrderedDict([('b', 20), ('d', None)])
-----dic----
{'a': None, 'b': None, 'c': None}
{'a': 1, 'b': 2}
dict_items([('a', 1), ('b', 2)])

Process finished with exit code 0


defaultdict

使用dict时,如果引用的Key不存在,就会抛出KeyError。如果希望key不存在时,返回一个默认值,就可以用defaultdict:

from collections import defaultdict

values = [11, 22, 33,44,55,66,77,88,99,90]

my_dict = defaultdict(list)

for value in  values:
if value>66:
my_dict['k1'].append(value)
else:
my_dict['k2'].append(value)
print(my_dict)


输出如下:

E:\python\python_sdk\python.exe E:/python/py_pro/4collections.py
defaultdict(<class 'list'>, {'k2': [11, 22, 33, 44, 55, 66], 'k1': [77, 88, 99, 90]})

Process finished with exit code 0


from collections import defaultdict

dic = defaultdict(lambda :"default")
dic["a"] = "a"
dic["b"] = "b"
for i in dic:
print(i)
print(dic["cc"])


输出如下:

E:\python\python_sdk\python.exe E:/python/py_pro/4collections.py
a
b
default

Process finished with exit code 0


Counter

Counter类的目的是用来跟踪值出现的次数。它是一个无序的容器类型,以字典的键值对形式存储,其中元素作为key,其计数作为value。计数值可以是任意的Interger(包括0和负数)。Counter类和其他语言的bags或multisets很相似。

from collections import Counter
c = Counter('abcdeabcdabcaba')
print(c)


输出如下:

E:\python\python_sdk\python.exe E:/python/py_pro/4collections.py
Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})

Process finished with exit code 0


time时间模块

1、print(“—时间戳timestamp—–”)

2、print(“-格式化的时间字符串(Format String)—”)

%y 两位数的年份表示(00-99)
%Y 四位数的年份表示(000-9999)
%m 月份(01-12)
%d 月内中的一天(0-31)
%H 24小时制小时数(0-23)
%I 12小时制小时数(01-12)
%M 分钟数(00=59)
%S 秒(00-59)
%a 本地简化星期名称
%A 本地完整星期名称
%b 本地简化的月份名称
%B 本地完整的月份名称
%c 本地相应的日期表示和时间表示
%j 年内的一天(001-366)
%p 本地A.M.或P.M.的等价符
%U 一年中的星期数(00-53)星期天为星期的开始
%w 星期(0-6),星期天为星期的开始
%W 一年中的星期数(00-53)星期一为星期的开始
%x 本地相应的日期表示
%X 本地相应的时间表示
%Z 当前时区的名称
%% %号本身


3、print(“–元组(struct_time)—”)



import time
print("---时间戳timestamp-----")
print(time.time())
time.sleep(1)

print("-格式化的时间字符串(Format String)---")
ret = time.strftime('%Y-%m-%d %a %H:%M:%S')
print(ret)

print("--元组(struct_time)---")
print(time.localtime())
print(time.gmtime())


输出如下:

E:\python\python_sdk\python.exe E:/python/py_pro/5time.py
---时间戳timestamp-----
1510657478.9145422
-格式化的时间字符串(Format String)---
2017-11-14 Tue 19:04:39
--元组(struct_time)---
time.struct_time(tm_year=2017, tm_mon=11, tm_mday=14, tm_hour=19, tm_min=4, tm_sec=39, tm_wday=1, tm_yday=318, tm_isdst=0)
time.struct_time(tm_year=2017, tm_mon=11, tm_mday=14, tm_hour=11, tm_min=4, tm_sec=39, tm_wday=1, tm_yday=318, tm_isdst=0)

Process finished with exit code 0


继续看时间的转换



#time.gmtime(时间戳)    #UTC时间,与英国伦敦当地时间一致
#time.localtime(时间戳) #当地时间。例如我们现在在北京执行这个方法:
# 与UTC时间相差8小时,UTC时间+8小时 = 北京时间
ret = time.localtime(3000000000)
print(ret)
print("--"*15)
print(time.mktime(ret))
print("--"*15)
ret = time.gmtime(3000000000)
print(ret)
print("--"*15)
print(time.mktime(ret))
print("--"*15)

#结构化时间转字符串
#def strftime(format, p_tuple=None)
ret2 = time.strftime('%c',ret)
print(ret2)
print("--"*15)

#字符串转结构化时间time.strptime(时间字符串,字符串对应格式)
print(time.strptime('1990-3-31','%Y-%m-%d'))
print("--"*15)
print(time.mktime(time.strptime('1990-3-31','%Y-%m-%d')))


输出如下:

E:\python\python_sdk\python.exe E:/python/py_pro/5time.py
time.struct_time(tm_year=2065, tm_mon=1, tm_mday=24, tm_hour=13, tm_min=20, tm_sec=0, tm_wday=5, tm_yday=24, tm_isdst=0)
------------------------------
3000000000.0
------------------------------
time.struct_time(tm_year=2065, tm_mon=1, tm_mday=24, tm_hour=5, tm_min=20, tm_sec=0, tm_wday=5, tm_yday=24, tm_isdst=0)
------------------------------
2999971200.0
------------------------------
Sat Jan 24 05:20:00 2065
------------------------------
time.struct_time(tm_year=1990, tm_mon=3, tm_mday=31, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=90, tm_isdst=-1)
------------------------------
638812800.0

Process finished with exit code 0




#time.asctime(结构化时间) 如果不传参数,直接返回当前时间的格式化串
print(time.asctime())

ret = time.localtime(1000000)
print(ret)
print(time.asctime(ret))
##time.ctime(时间戳)  如果不传参数,直接返回当前时间的格式化串
print(time.ctime())
print(time.ctime(1000000))


输出如下:

E:\python\python_sdk\python.exe E:/python/py_pro/5time.py
Tue Nov 14 19:51:30 2017
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=12, tm_hour=21, tm_min=46, tm_sec=40, tm_wday=0, tm_yday=12, tm_isdst=0)
Mon Jan 12 21:46:40 1970
Tue Nov 14 19:51:30 2017
Mon Jan 12 21:46:40 1970

Process finished with exit code 0


练习2个时间戳过了多少时间

用了一个很巧妙的方法,将2个时间差计算出来,然后跟格林尼治时间比较

import time
true_time=time.mktime(time.strptime('2017-09-11 11:30:00','%Y-%m-%d %H:%M:%S'))
time_now=time.mktime(time.strptime('2017-09-12 10:00:06','%Y-%m-%d %H:%M:%S'))
dif_time=time_now-true_time
struct_time=time.gmtime(dif_time)
print('过去了%d年%d月%d天%d小时%d分钟%d秒'%(struct_time.tm_year-1970,struct_time.tm_mon-1,
struct_time.tm_mday-1,struct_time.tm_hour,
struct_time.tm_min,struct_time.tm_sec))


输出如下:

过去了0年0月0天22小时30分钟6秒


sys模块模块

import sys

# sys.path的第一位元素是当前被执行的python文件所在的地址
# 之后的地址依次是python内部的库
print(sys.path)

#sys.argv的第一个值是固定的的,就是这个文件的名字
#之后的参数 是在控制台执行py文件的时候传入的参数 python 6sys.py safly 123
#我们可以用这些参数来直接完成一些校验类的工作

print(sys.argv)
args_lst = sys.argv  #['6sys.py', 'safly', '123']
if len(args_lst) ==3 and args_lst[1] == 'safly' and args_lst[2] == '123':
print('执行程序了')
else:
sys.exit()


在控制台输入

E:\python\py_pro>python 6sys.py safly 123
['E:\\python\\py_pro', 'E:\\python\\python_sdk\\python36.zip', 'E:\\python\\python_sdk\\DLLs', 'E:\\python\
\python_sdk\\lib', 'E:\\python\\python_sdk', 'E:\\python\\python_sdk\\lib\\site-packages']
['6sys.py', 'safly', '123']
执行程序了

E:\python\py_pro>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: