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中方案.