创新互联Python教程:有用的20个python代码段(3)

有用的20个python代码段(3):

目前累计服务客户成百上千,积累了丰富的产品开发及服务经验。以网站设计水平和技术实力,树立企业形象,为客户提供做网站、成都网站设计、网站策划、网页设计、网络营销、VI设计、网站改版、漏洞修补等服务。创新互联始终以务实、诚信为根本,不断创新和提高建站品质,通过对领先技术的掌握、对创意设计的研究、对客户形象的视觉传递、对应用系统的结合,为客户提供更好的一站式互联网解决方案,携手广大客户,共同发展进步。

1、检查给定字符串是否是回文(Palindrome)

my_string = "abcba"
m if my_string == my_string[::-1]:
    print("palindrome")
else:
    print("not palindrome")
# Output
# palindrome

2、列表的要素频率

有多种方式都可以完成这项任务,而我最喜欢用Python的Counter 类。Python计数器追踪每个要素的频率,Counter()反馈回一个字典,其中要素是键,频率是值。

也使用most_common()功能来获得列表中的most_frequent element。

# finding frequency of each element in a list
from collections import Counter
my_list = ['a','a','b','b','b','c','d','d','d','d','d']
count = Counter(my_list) # defining a counter object
print(count) # Of all elements
# Counter({'d': 5, 'b': 3, 'a': 2, 'c': 1})
print(count['b']) # of individual element
# 3
print(count.most_common(1)) # most frequent element
# [('d', 5)]

3、查找两个字符串是否为anagrams

Counter类的一个有趣应用是查找anagrams。

anagrams指将不同的词或词语的字母重新排序而构成的新词或新词语。

如果两个字符串的counter对象相等,那它们就是anagrams。

From collections import Counter
str_1, str_2, str_3 = "acbde", "abced", "abcda"
cnt_1, cnt_2, cnt_3  = Counter(str_1), Counter(str_2), Counter(str_3)
if cnt_1 == cnt_2:
    print('1 and 2 anagram')
if cnt_1 == cnt_3:
    print('1 and 3 anagram')

4、使用try-except-else块

通过使用try/except块,Python 中的错误处理得以轻松解决。在该块添加else语句可能会有用。当try块中无异常情况,则运行正常。

如果要运行某些程序,使用 finally,无需考虑异常情况。

a, b = 1,0
try:
    print(a/b)
    # exception raised when b is 0
except ZeroDivisionError:
    print("division by zero")
else:
    print("no exceptions raised")
finally:
    print("Run this always")

更多Python知识,请关注:Python自学网!!

新闻标题:创新互联Python教程:有用的20个python代码段(3)
文章出自:http://www.hantingmc.com/qtweb/news36/19586.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联