提升Python代码可读性的10个实用技巧
本文整理了10个提升Python代码可读性的实用技巧,涵盖字符串反转、大小写处理、去重、变量交换、排序、列表推导式、字符串合并与拆分、回文检测及元素统计。通过具体代码示例,帮助开发者写出更简洁高效的Python代码。
1. 字符串反转
实现字符串反转有多种方式,本文重点介绍两种:利用切片操作和使用Python内置的reversed函数。
# -!- coding: utf-8 -!- string = 'hello world' # 方法1 new_str = string[::-1] ic(new_str) # 方法二 new_str2 = ''.join(reversed(string)) ic(new_str2) ''' ic| new_str: 'dlrow olleh' ic| new_str2: 'dlrow olleh' '''
2. 首字母大写
此处介绍两种方法,主要区别在于**capitalize()**仅将字符串首字母大写。
而**title()**方法会将字符串中每个单词的首字母都转换为大写。
# 首字母大写 string = 'hello python and world' # 方法一 new_str = string.capitalize() ic(new_str) # 方法二 new_str2 = string.title() ic(new_str2) ''' ic| new_str: 'Hello python and world' ic| new_str2: 'Hello Python And World' '''
3. 查询唯一元素
利用set数据类型的唯一性特征,可以快速提取字符串中的唯一字符元素。
string = 'hellohellohello'
new_str = set(string)
# set类型
ic(new_str)
# 字符串类型
new_str = ''.join(new_str)
ic(new_str)
'''
ic| new_str: {'l', 'o', 'h', 'e'}
ic| new_str: 'lohe'
'''4. 变量交换
在python中,变量交换比Java更为简便。无需定义第三个临时变量,直接通过元组解包即可实现两个变量的值互换。
a = 'hello' b = 'world' ic(a+b) # 直接交换两个变量 a, b = b, a ic(a+b) ''' ic| a+b: 'helloworld' ic| a+b: 'worldhello' '''
5. 列表排序
列表排序提供两种常用方式:一是列表对象自带的**sort()方法;二是使用Python内置的sorted()**函数。
score = [88, 99, 91, 85, 94, 85, 94, 78, 100, 80]
# 方法一
new_score = sorted(score)
ic('默认升序:', new_score)
score = [57, 29, 11, 27, 84, 34, 87, 25, 70, 60]
# 方法二
new_score2 = sorted(score, reverse=True)
ic('设置降序', new_score2)
'''
ic| '默认升序:', new_score: [78, 80, 85, 85, 88, 91, 94, 94, 99, 100]
ic| '设置降序', new_score2: [87, 84, 70, 60, 57, 34, 29, 27, 25, 11]
'''6. 列表推导式
利用列表推导式,可以高效地生成新列表,或基于现有列表筛选出符合特定条件的元素。
# 生成10个10-100以内随机整数 numbers = [random.randint(10, 100) for x in range(10)] ic(numbers) # 输入5折后的价格 price = [800, 500, 400, 860, 780, 520, 560] half_price = [(x*0.5)for x in price] ic(half_price) ''' ic| numbers: [64, 22, 80, 70, 34, 81, 74, 35, 85, 12] ic| half_price: [400.0, 250.0, 200.0, 430.0, 390.0, 260.0, 280.0] '''
7. 合并字符串
合并字符串时,推荐使用string模块提供的.join()方法来实现。
lists = ['hello', 'world', 'python', 'java', 'c++'] # 合并字符串 new_str = ' '.join(lists) ic(new_str) ''' ic| new_str: 'hello world python java c++' '''
8. 拆分字符串
拆分字符串主要依赖string对象的split()方法,可根据指定分隔符将字符串分割为列表。
string = 'hello world python java c++'
string2 = 'hello|world|python|java|c++'
# 拆分字符串
new_str = string.split(' ')
ic(new_str)
new_str2 = string2.split('|')
ic(new_str2)
'''
ic| new_str: ['hello', 'world', 'python', 'java', 'c++']
ic| new_str2: ['hello', 'world', 'python', 'java', 'c++']
'''9. 回文串检测
回文串是指如aba、abba、cccbccc、aaaa等左右对称的字符串。借助前文提到的切片技术,可以便捷地检测此类特殊字符串序列。
str = '20211202'
if str == str[::-1]:
print('yes')
else:
print('no')
'''
yes
'''10. 统计列表元素出现次数
统计列表中各元素的出现频次,可使用collections 模块中的Counter类来实现。
from collections import Counter
lists = ['a', 'a', 'b', 'b', 'b', 'c', 'd', 'd', 'd', 'd', 'd']
# 统计所有元素出现的次数
counts = Counter(lists)
ic(counts)
# 统计某一元素出现的次数
ic(counts['d'])
# 统计出现最多次数的一个元素
ic(counts.most_common(1))
'''
ic| counts: Counter({'d': 5, 'b': 3, 'a': 2, 'c': 1})
ic| counts['d']: 5
ic| counts.most_common(1): [('d', 5)]
'''
以上就是关于分享10提高 Python 代码的可读性的技巧的全部内容,更多相关提高 Python 代码可读性内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









