有用的20个python代码段(3):
1、检查给定字符串是否是回文(Palindrome)
my_string="abcba" mifmy_string==my_string[::-1]: print("palindrome") else: print("notpalindrome") #Output #palindrome
2、列表的要素频率
有多种方式都可以完成这项任务,而我最喜欢用Python的Counter 类。Python计数器追踪每个要素的频率,Counter()反馈回一个字典,其中要素是键,频率是值。
也使用most_common()功能来获得列表中的most_frequent element。
#findingfrequencyofeachelementinalist fromcollectionsimportCounter my_list=['a','a','b','b','b','c','d','d','d','d','d'] count=Counter(my_list)#definingacounterobject print(count)#Ofallelements #Counter({'d':5,'b':3,'a':2,'c':1}) print(count['b'])#ofindividualelement #3 print(count.most_common(1))#mostfrequentelement #[('d',5)]
3、查找两个字符串是否为anagrams
Counter类的一个有趣应用是查找anagrams。
anagrams指将不同的词或词语的字母重新排序而构成的新词或新词语。
如果两个字符串的counter对象相等,那它们就是anagrams。
FromcollectionsimportCounter str_1,str_2,str_3="acbde","abced","abcda" cnt_1,cnt_2,cnt_3=Counter(str_1),Counter(str_2),Counter(str_3) ifcnt_1==cnt_2: print('1and2anagram') ifcnt_1==cnt_3: print('1and3anagram')
4、使用try-except-else块
通过使用try/except块,Python 中的错误处理得以轻松解决。在该块添加else语句可能会有用。当try块中无异常情况,则运行正常。
如果要运行某些程序,使用 finally,无需考虑异常情况。
a,b=1,0 try: print(a/b) #exceptionraisedwhenbis0 exceptZeroDivisionError: print("divisionbyzero") else: print("noexceptionsraised") finally: print("Runthisalways")
更多Python知识,请关注:Python自学网!!