python 常用技巧
2022/6/8 1:21:20
本文主要是介绍python 常用技巧,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
简介
在实际项目或者面试中会遇到一些常用的python小技巧,其实就是所谓的内置模块,方便了开发。
字符串倒转
s = 'ASDFGH' print(s[-1::-1]) print(s[::-1])
HGFDSA HGFDSA
英文单词的首字母大写
data = 'my name is tom' print(data.title()) print(data)
My Name Is Tom my name is tom
字符串去重
不按照顺序显示
data = 'aaasssssaafffeffgrtgssffg' print(''.join(set(data)))
sertfga
按照第一次出现顺序显示
方法一:使用遍历添加到列表
data = 'aaasssssaafffeffgrtgssffg' ret = [] for item in data: if ret.count(item) == 0: ret.append(item) print(''.join(ret))
asfegrt
方法二:使用set,再使用sort根据key值的索引进行排序
data = 'aaasssssaafffeffgrtgssffg' data_list = list(data) lists = list(set(data_list)) print(lists) lists.sort(key=data_list.index) print(lists) print(''.join(lists))
['s', 'f', 'g', 'a', 'e', 'r', 't'] ['a', 's', 'f', 'e', 'g', 'r', 't'] asfegrt
字符串拆分
普通字符串拆分
data = 'hello, everyone, world\nhello, everyone, world' print(data.split(',')) # 以换行符为分割,默认不显示换行符 print(data.splitlines()) print(data.splitlines(True))
['hello', ' everyone', ' world\nhello', ' everyone', ' world'] ['hello, everyone, world', 'hello, everyone, world'] ['hello, everyone, world\n', 'hello, everyone, world']
路径拆分
import os path = os.path.join(os.path.dirname(__file__), 'test.text') # 分割文件后缀名 print(os.path.splitext(path)) # 以系统平台分割 print(path.split(os.sep))
('/home/ts/flask_study/python常用技巧/test', '.text') ['', 'home', 'ts', 'flask_study', 'python常用技巧', 'test.text']
字符串连接
l = ['my', 'name', 'is', 'tom'] print(' '.join(l))
my name is tom
查看列表中各元素的个数
words = [ "look", "into", "my", "eyes", "look", "into", "my", "eyes", "the", "eyes", "the", "eyes", "the", "eyes", "the", "eyes", "my", "eyes", "you're", "under", "my", "eyes", "you're", "under" ] # 使用collection的counter from collections import Counter ret = Counter(words) print(ret) # 次数出现最多的前三个 print(ret.most_common(3)) # 查看ret的所有的数量 print(sum(ret.values())) # 列表推导式/列表生成式 ret = [(item,words.count(item)) for item in words] print(set(ret))
Counter({'eyes': 8, 'my': 4, 'the': 4, 'look': 2, 'into': 2, "you're": 2, 'under': 2}) [('eyes', 8), ('my', 4), ('the', 4)] 24 {("you're", 2), ('look', 2), ('my', 4), ('into', 2), ('eyes', 8), ('under', 2), ('the', 4)}
两字典合并
dict_1 = {'apple': 9, 'banana': 6} dict_2 = {'grape': 4, 'orange': 8} # 将字典解包成对应元素并进行合成 combined_dict = {**dict_1, **dict_2} print(combined_dict) # 使用自带的update print(dict_1.update(dict_2)) print(dict_1) # 并集 print(dict(dict_1.items() | dict_2.items())) # 交集,只显示最后 print(dict(dict_1.items() & dict_2.items()))
{'apple': 9, 'banana': 6, 'grape': 4, 'orange': 8} None {'apple': 9, 'banana': 6, 'grape': 4, 'orange': 8} {'banana': 6, 'orange': 8, 'apple': 9, 'grape': 4} {'grape': 4, 'orange': 8}
列表的扁平化
一个列表中有多个列表嵌套。
使用第三方模块iteration_utilities
from iteration_utilities import deepflatten l = [[1,2,3],[4,[5],[6,7]],[8,[9,[10]]]] print(list(deepflatten(l, depth=3)))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
递归获取
l = [[1,2,3],[4,[5],[6,7]],[8,[9,[10]]]] def unfold_list(list_data): for item in list_data: if isinstance(item, list): yield from unfold_list(item) else: yield item print(list(unfold_list(l)))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
查看列表当中是否存在重复值
l1 = [1,2,3,4] l2 = [2,2,1,3] l3 = [1,2,3,3] def unique(l): return not len(l) == len(set(l)) def unique2(l): for item in l: if l.count(item) > 1: return True return False import time start = time.time() print(unique(l1)) print(unique(l2)) print(unique(l3)) print(time.time() - start) start = time.time() print(unique2(l1)) print(unique2(l2)) print(unique2(l3)) print(time.time() - start)
False True True 2.2172927856445312e-05 False True True 6.67572021484375e-06
数组的转置
array = [['a', 'b'], ['c', 'd'], ['e', 'f']] print(*array) print(list(zip(*array)))
['a', 'b'] ['c', 'd'] ['e', 'f'] [('a', 'c', 'e'), ('b', 'd', 'f')]
获取两个列表的不同元素
l1 = [1,2,3,4] l2 = [2,2,1,3,5] print(set(l1).difference(set(l2))) print(set(l2).difference(set(l1))) print(set(l1).difference(set(l2)) | set(l2).difference(set(l1)))
{4} {5} {4, 5}
将两列表变成键值对
l1 = ['A','B','C','D'] l2 = [2,2,1,3] print(dict(zip(l1,l2)))
{'A': 2, 'B': 2, 'C': 1, 'D': 3}
对字典进行排序,根据键、值
d = {'apple': 9, 'grape': 4, 'banana': 6, 'orange': 8} # 以键排序 print(dict(sorted(d.items(), key=lambda d:d[0]))) # 以值排序 print(dict(sorted(d.items(), key=lambda d:d[1]))) import operator # 以键排序 # operator.itemgetter获取第一个下标的元素 print(dict(sorted(d.items(), key=operator.itemgetter(0)))) # 以值排序 print(dict(sorted(d.items(), key=operator.itemgetter(1))))
{'apple': 9, 'banana': 6, 'grape': 4, 'orange': 8} {'grape': 4, 'banana': 6, 'orange': 8, 'apple': 9} {'apple': 9, 'banana': 6, 'grape': 4, 'orange': 8} {'grape': 4, 'banana': 6, 'orange': 8, 'apple': 9}
列表中最大/最小值的索引
list1 = [20, 30, 50, 70, 90] def max_index(list_test): return max(range(len(list_test)), key = list_test.__getitem__) def min_index(list_test): return min(range(len(list_test)), key = list_test.__getitem__) print(max_index(list1)) print(min_index(list1))
4 0
这篇关于python 常用技巧的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-02封装学习:Python面向对象编程基础教程
- 2024-12-28Python编程基础教程
- 2024-12-27Python编程入门指南
- 2024-12-27Python编程基础
- 2024-12-27Python编程基础教程
- 2024-12-27Python编程基础指南
- 2024-12-24Python编程入门指南
- 2024-12-24Python编程基础入门
- 2024-12-24Python编程基础:变量与数据类型
- 2024-12-23使用python部署一个usdt合约,部署自己的usdt稳定币