Python有非常多有趣使用的技巧雅潭,下面列舉20個(gè)短小精煉的用法,其中既包含常規(guī)語(yǔ)法但绕,又有第三方庫(kù)的妙用救崔,體現(xiàn)了python簡(jiǎn)單即美的編程哲學(xué)惶看。
- 快速實(shí)現(xiàn)字頻統(tǒng)計(jì)
from collections import Counter
words = '''我明白你的意思,你的意思就是想意思意思六孵,但是你不明白我的意思纬黎,我的意思是你不用意思意思。'''
word_counts = Counter(words)
top_three = word_counts.most_common(3)
print(top_three)
# 輸出:[('意', 8), ('思', 8), ('你', 4)]
- 漢字轉(zhuǎn)拼音
import pypinyin
words = "床前明月光"
pypinyin.pinyin(words)
# 輸出:[['chuáng'], ['qián'], ['míng'], ['yuè'], ['guāng']]
- 查看某個(gè)文件夾里是否有python文件(或其他格式文件)
import os
files = os.listdir("E:\\testfile\\")
if any(name.endswith('.py') for name in files):
print(1)
- 快速打印字符串
row = ["我", "愛(ài)", "python"]
print(*row,sep="")
# 輸出:我愛(ài)python
- 計(jì)算兩個(gè)日期間隔天數(shù)
from datetime import date
d1 = date(2020,1,1)
d2 = date(2020,9,13)
print(abs(d2-d1).days)
# 輸出:256
- 字符串拆解為鍵值對(duì)
比如'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 = 1
b = 2
a, b = b, a
- 將值追加到字典某個(gè)鍵下的列表中
d = {}
d.setdefault(2, []).append(23)
d.setdefault(2, []).append(11)
d[2]
# 輸出:[23, 11]
- 返回列表中出現(xiàn)次數(shù)最多的元素
test = [1, 2, 3, 5, 2, 2, 3, 1, 2, 6, 2]
print(max(set(test), key = test.count))
# 輸出:2
- 查看某個(gè)變量占用內(nèi)存大小
import sys
x = 1
print(sys.getsizeof(x))
# 輸出:28
- 隨機(jī)返回幾個(gè)字母組成的單詞
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']
- 打印進(jìn)度條
import time
import sys
for progress in range(100):
time.sleep(0.1)
sys.stdout.write("Download progress: %d%% \r" % (progress) )
sys.stdout.flush()
- 快速反轉(zhuǎn)字符串
a = 'Python is a powerful languange.'
print(a[::-1])
# 輸出:.egnaugnal lufrewop a si nohtyP
- 找出兩個(gè)列表中不一樣的元素
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']
- 刪除列表中的重復(fù)項(xiàng)
listNumbers = [20, 22, 24, 26, 28, 28, 20, 30, 24]
list(set(listNumbers))
# 輸出:[20, 22, 24, 26, 28, 30]
- 將兩個(gè)列表變?yōu)樽值?/li>
ItemId = [54, 65, 76]
names = ["Hard Disk", "Laptop", "RAM"]
itemDictionary = dict(zip(ItemId, names))
print(itemDictionary)
# 輸出:{54: 'Hard Disk', 65: 'Laptop', 76: 'RAM'}
- 移除字符串中的標(biāo)點(diǎn)
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~劫窒,本今。!烛亦?'''
my_str = "你好诈泼,!!我的網(wǎng)名叫作:隔-壁-老-王懂拾。"
# 移除標(biāo)點(diǎn)
no_punct = ""
for char in my_str:
if char not in punctuations:
no_punct = no_punct + char
print(no_punct)
# 輸出:你好我的名字叫作:隔壁老王
- 創(chuàng)建一個(gè)文件(如果該文件不存在)
import os
MESSAGE = '該文件已經(jīng)存在.'
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)
- 從函數(shù)中返回多個(gè)值
def f():
return 1,2,3,4
a,b,c,d = f()
print(a,b,c,d)
# 輸出:1,2,3,4