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

361次阅读
没有评论

有用的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")
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-06-15发表,共计1340字。
新手QQ群:570568346,欢迎进群讨论 Python51学习