3.Python中的统计与排序


1.字符串替换
string.replace(str1, str2,  num=string.count(str1))
str = "this is string example....wow!!! this is really string";
print str.replace("is", "was", 1);


2.统计list相同元素的频率
import re
from collections import Counter
DATA = "In this paper,of of of a a a we propose a new multi-hop scheme of the single unitary transformation method (SUTM) to realize the long-distance teleportation of an unknown W state"
list1=re.findall(r"[\w']+", DATA)
c1=Counter(list1)
print(c1)
#结果
Counter({'of': 5, 'a': 4, 'the': 2, 'In': 1, 'this': 1, 'paper': 1, 'we': 1, 'propose': 1, 'new': 1, 'multi': 1, 'hop': 1, 'scheme': 1, 'single': 1, 'unitary': 1, 'transformation': 1, 'method': 1, 'SUTM': 1, 'to': 1, 'realize': 1, 'long': 1, 'distance': 1, 'teleportation': 1, 'an': 1, 'unknown': 1, 'W': 1, 'state': 1})


3.从一个列表/字典生成带初始值的字典
c2=dict.fromkeys(c1,'00')
print(c2)
#结果
{'In': '00', 'this': '00', 'paper': '00', 'of': '00', 'a': '00', 'we': '00', 'propose': '00', 'new': '00', 'multi': '00', 'hop': '00', 'scheme': '00', 'the': '00', 'single': '00', 'unitary': '00', 'transformation': '00', 'method': '00', 'SUTM': '00', 'to': '00', 'realize': '00', 'long': '00', 'distance': '00', 'teleportation': '00', 'an': '00', 'unknown': '00', 'W': '00', 'state': '00'}

4.sorted使用
c3=sorted(zip(c1.values(),c1.keys()),reverse=True)
print(c3)
#结果
[(5, 'of'), (4, 'a'), (2, 'the'), (1, 'we'), (1, 'unknown'), (1, 'unitary'), (1, 'transformation'), (1, 'to'), (1, 'this'), (1, 'teleportation'), (1, 'state'), (1, 'single'), (1, 'scheme'), (1, 'realize'), (1, 'propose'), (1, 'paper'), (1, 'new'), (1, 'multi'), (1, 'method'), (1, 'long'), (1, 'hop'), (1, 'distance'), (1, 'an'), (1, 'W'), (1, 'SUTM'), (1, 'In')]

5.sorted+lambda排序
c4=sorted(c1.items(), key=lambda x: x[1],reverse=True)
print(c4)
[('of', 5), ('a', 4), ('the', 2), ('In', 1), ('this', 1), ('paper', 1), ('we', 1), ('propose', 1), ('new', 1), ('multi', 1), ('hop', 1), ('scheme', 1), ('single', 1), ('unitary', 1), ('transformation', 1), ('method', 1), ('SUTM', 1), ('to', 1), ('realize', 1), ('long', 1), ('distance', 1), ('teleportation', 1), ('an', 1), ('unknown', 1), ('W', 1), ('state', 1)]

6.使用timeit进行分析

import timeit

def a():

   sorted(c1.items(), key=lambda x: x[1],reverse=True)

timeit.timeit(a)#可以用来统计时间


与第4部分比较,前面几项是相同的,但从this开始结果不同,因而可以看出 5中比较不充分,比较次数较少,4中比较充分,但循环次数很多.实测结果也验证这个结论,推荐第5中方案.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值