教程集 www.jiaochengji.com
教程集 >  Python编程  >  Python入门  >  正文 有用的20个python代码段(3)

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

发布时间:2021-03-06   编辑:jiaochengji.com
教程集为您提供有用的20个python代码段(3)等资源,欢迎您收藏本站,我们将为您提供最新的有用的20个python代码段(3)资源

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

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自学网!!

您可能感兴趣的文章:
有用的20个python代码段(4)
初识Python-Python的历史与优缺点
python的类的方法为什么有个self
有用的20个python代码段(1)
Python编程语言特征
Python的特点(优点和缺点)
Python是一门怎样的编程语言
Python之装饰器简介
fluent python是什么意思
python中idle是什么

[关闭]
~ ~