品易云推流 关闭
文章详情页
文章 > Python基础教程 > 有用的20个python代码段(3)

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

头像

尤及

2020-06-17 16:44:012186浏览 · 0收藏 · 0评论

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

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图