博客列表 >Python高效编程技巧实战(11)

Python高效编程技巧实战(11)

yeyiluLAMP
yeyiluLAMP原创
2017年10月05日 15:06:41758浏览

snipaste20171005_122929.png

python中的字典是无序性的,使用标准库collections中的OrderedDict,使字典具备有序性

In [1]: d = {}

In [2]: d['Jim'] = (1,30)

In [3]: d['Leo'] = (2,40)

In [4]: d['Bob'] = (3,43)

In [5]: d
Out[5]: {'Leo': (2, 40), 'Bob': (3, 43), 'Jim': (1, 30)}

In [6]: for x in d: print(x)
Leo
Bob
Jim

In [7]: for x in d: print(x)
Leo
Bob
Jim

In [8]: from collections import OrderedDict

In [9]: d = OrderedDict()

In [10]: d
Out[10]: OrderedDict()

In [11]: for x in d: print(x)

In [12]: d['Jim'] = (1,30)

In [13]: d['Leo'] = (2,40)

In [14]: d['Bob'] = (3,43)

In [15]: for x in d: print(x)
Jim
Leo
Bob

In [16]: d
Out[16]: OrderedDict([('Jim', (1, 30)), ('Leo', (2, 40)), ('Bob', (3, 43))])




 vim orderdict.py


 1    from time import time
 2    from random import randint
 3    from collections import OrderedDict
 4    
 5    d = OrderedDict()
 6    player = list('ABCDEFGH')
 7    start = time()
 8    
 9    for i in range(len(player)):
10        input()
11        p = player.pop(randint(0,7 - i))
12        end = time()
13        print(i + 1,p,end - start,)
14        d[p] = (i + 1,end -start)
15    
16    print()
17    print('*' * 20)
18    for k,v in d.items():
19        print(k,v) 
20



In [45]: !python3 orderdict.py

1 G 0.7850325107574463

2 E 1.2250711917877197

3 C 1.6086609363555908

4 A 1.9764859676361084

5 B 2.3427579402923584

6 D 2.703601837158203

7 F 3.3351752758026123

8 H 3.8562939167022705

********************
G (1, 0.7850325107574463)
E (2, 1.2250711917877197)
C (3, 1.6086609363555908)
A (4, 1.9764859676361084)
B (5, 2.3427579402923584)
D (6, 2.703601837158203)
F (7, 3.3351752758026123)
H (8, 3.8562939167022705)


声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议