关于Python的20个奇技淫巧

做一个柔情的程序猿

共 3600字,需浏览 8分钟

 · 2021-04-10

一、快速实现字频统计

from collections import Counter
words = '''我明白你的意思,你的意思就是想意思意思,但是你不明白我的意思,我的意思是你不用意思意思。'''word_counts = Counter(words) top_three = word_counts.most_common(3) print(top_three)
# 输出:[('意', 8), ('思', 8), ('你', 4)]

二、汉字转拼音

import pypinyinwords = "床前明月光"pypinyin.pinyin(words)
# 输出:[['chuáng'], ['qián'], ['míng'], ['yuè'], ['guāng']]

三、查看某个文件夹里是否有python文件(或其他格式文件)

import os files = os.listdir("E:\\testfile\\") if any(name.endswith('.py') for name in files):    print(1)

四、快速打印字符串


row = ["我", "爱", "python"] print(*row,sep="")
# 输出:我爱python

五、计算两个日期间隔天数

from datetime import dated1 = date(2020,1,1) d2 = date(2020,9,13) print(abs(d2-d1).days)
# 输出:256

六、字符串拆解为键值对

比如'x=11,y=20'拆解成{'x'42.0'y'1.0}
kvp = lambda elem,t,i: t(elem.split('=')[i]) parse_kvp_str = lambda args : dict([(kvp(elem,str,0), kvp(elem,float,1)) for elem in args.split(',')]) parse_kvp_str('x=11,y=20') 
# 输出:{'x': 42.0, 'y': 1.0}

七、变量值交换

a = 1b = 2a, b = b, a

八、将值追加到字典某个键下的列表中

d = {} d.setdefault(2, []).append(23) d.setdefault(2, []).append(11) d[2] 
# 输出:[23, 11]

九、返回列表中出现次数最多的元素

test = [1, 2, 3, 5, 2, 2, 3, 1, 2, 6, 2] print(max(set(test), key = test.count)) 
# 输出:2

十、查看某个变量占用内存的大小

import sys x = 1print(sys.getsizeof(x)) 
# 输出:28

十一、随机返回几个字母组成的单词

import string, random randword = lambda n: "".join([random.choice(string.ascii_letters) for i in range(n)])
# 输出:'qsNWZF'

十二、从混乱的字符串中分解出单词

words = lambda text: ''.join(c if c.isalnum() else ' ' for c in text).split() words('Johnny.Appleseed!is:a*good&farmer') 
# 输出:['Johnny''Appleseed''is''a''good''farmer']

十三、打印进度条

import time import sys for progress in range(100):   time.sleep(0.1)   sys.stdout.write("Download progress: %d%%   \r" % (progress) )    sys.stdout.flush() 

十四、快速反转字符串

a = 'Python is a powerful languange.'print(a[::-1])
# 输出:.egnaugnal lufrewop a si nohtyP

十五、找出两个列表中不一样的元素

list1 = ['Scott', 'Eric', 'Kelly', 'Emma', 'Smith']list2 = ['Scott', 'Eric', 'Kelly']
set1 = set(list1)set2 = set(list2)
list3 = list(set1.symmetric_difference(set2))print(list3)
# 输出:['Emma', 'Smith']

十六、删除列表中的重复项

listNumbers = [20, 22, 24, 26, 28, 28, 20, 30, 24]list(set(listNumbers))
# 输出:[20, 22, 24, 26, 28, 30]

十七、将两个列表变成字典

ItemId = [54, 65, 76]names = ["Hard Disk", "Laptop", "RAM"]itemDictionary = dict(zip(ItemId, names))print(itemDictionary)
# 输出:{54: 'Hard Disk', 65: 'Laptop', 76: 'RAM'}

十八、移除字符换中的标点

punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~,。!?'''my_str = "你好,!!我的网名叫作:隔-壁-老-王。"
# 移除标点no_punct = ""for char in my_str: if char not in punctuations: no_punct = no_punct + char
print(no_punct)
# 输出:你好我的名字叫作:隔壁老王

十九、创建一个文件(如果文件不存在)

import os  
MESSAGE = '该文件已经存在.'TESTDIR = 'testdir'try: home = os.path.expanduser("~") print(home)
if not os.path.exists(os.path.join(home, TESTDIR)): os.makedirs(os.path.join(home, TESTDIR)) else: print(MESSAGE)except Exception as e: print(e)

二十、从函数中返回多个值

def f():    return 1,2,3,4 
a,b,c,d = f()print(a,b,c,d)
# 输出:1,2,3,4

推荐阅读

(点击标题可跳转阅读)

看到这些代码,我自叹不如!!!

通俗易懂之最小二乘法(附matlab和python例子实现)

数据处理工具--Pandas模块

PyMySQL数据库搭建

教你用Python制作实现自定义字符大小的简易小说阅读器

小程序云开发项目的创建与配置

汇总超全Matplotlib可视化最有价值的 50 个图表(附 Python 源代码)(一)

超详细讲解CTC理论和实战

ODBC连接主流数据库的配置方法

教你用python进行数字化妆,可爱至极

加速Python列表和字典,让你代码更加高效

老铁,三连支持一下,好吗?↓↓↓


点分享

点点赞

点在

浏览 25
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报