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'])#ofinpidualelement #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) #exceptionraisedwhenbis exceptZeroDivisionError: print("pisionbyzero") else: print("noexceptionsraised") finally: print("Runthisalways")
更多Python知识,请关注:Python自学网!!