博主信息
博文 41
粉丝 0
评论 1
访问量 48493
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
Python高效编程技巧实战(11)
yeyiluLAMP
原创
948人浏览过

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举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学