分享一些非常實(shí)用的Python小技巧
1.唯一性
以下方法可以檢查給定列表是否有重復(fù)的地方,可用set()的屬性將其從列表中刪除。
x = [1,1,2,2,3,2,3,4,5,6] y = [1,2,3,4,5] len(x)== len(set(x)) # False len(y)== len(set(y)) # True
2.變位詞(相同字母異序詞)
此方法可用于檢查兩個字符串是否為變位詞。
from collections import Counter
>>> Counter('abadfsdafsdfjsdaf')
Counter({'a': 4, 'd': 4, 'f': 4, 's': 3, 'b': 1, 'j': 1})
def anagram(first, second):
return Counter(first) == Counter(second)
anagram("abcd3", "3acdb") # True
3.內(nèi)存
此代碼段可用于檢查對象的內(nèi)存使用情況。
import sys variable = 30 print(sys.getsizeof(variable)) # 28
4.字節(jié)大小
此方法可輸出字符串的字節(jié)大小。
print(len(''.encode('utf-8')))# 0
print(len('hellow sdfsdaf'.encode('utf-8'))) # 14
5.打印N次字符串
此代碼段無需經(jīng)過循環(huán)操作便可多次打印字符串。
n = 2; s ="Programming"; print(s * n); # ProgrammingProgramming
6.首字母大寫
以下代碼片段只利用了title(),就能將字符串中每個單詞的首字母大寫。
s = "programming is awesome" print(s.title()) # Programming Is Awesome
7.列表細(xì)分
該方法將列表細(xì)分為特定大小的列表。
>>> list = list(range(12)) >>> size=3 >>> [list[i:i+size] for i in range(0,len(list), size)] [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]] >>>
8.壓縮
以下代碼使用filter()從,將錯誤值(False、None、0和“ ”)從列表中刪除。
list(filter(bool, [0, 1, False, 2, '', 3, 'a', 's', 34]))
9.計數(shù)
以下代碼可用于調(diào)換2D數(shù)組排列。
array = [['a', 'b'], ['c', 'd'], ['e', 'f']]
transposed = zip(*array)
print(transposed) # [('a', 'c', 'e'), ('b', 'd', 'f')]
10.鏈?zhǔn)奖容^
以下代碼可對各種運(yùn)算符進(jìn)行多次比較。
a = 3 print( 2 < a < 8) # True print(1 == a < 2) # False
11.逗號分隔
此代碼段可將字符串列表轉(zhuǎn)換為單個字符串,同時將列表中的每個元素用逗號隔開。
hobbies = ["basketball", "football", "swimming"]
print("My hobbies are: " + ", ".join(hobbies)) # My hobbies are: basketball, football, swimming
12.元音計數(shù)
此方法可計算字符串中元音(“a”、“e”、“i”、“o”、“u”)的數(shù)目。
import re print(len(re.findall(r'[aeiou]', 'foobar', re.IGNORECASE))) # 3 print(len(re.findall(r'[aeiou]', 'gym', re.IGNORECASE))) # 0
13.首字母小寫
此方法可將給定字符串的首字母轉(zhuǎn)換為小寫模式。
'FooBar'[:1].lower() + 'FooBar'[1:] # 'fooBar' 'FooBar'[:1].lower() + 'FooBar'[1:] # 'fooBar'
14.展開列表
下列代碼采用了遞歸法展開潛在的深層列表。
def spread(arg):
ret = []
for i in arg:
if isinstance(i, list):
ret.extend(i)
else:
ret.append(i)
return ret
def deep_flatten(lst):
result = []
result.extend(
spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst))))
return result
deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]
print(deep_flatten([1, [2], [[3], 4], 5])) # [1,2,3,4,5]
15.尋找差異
此方法僅保留第一個迭代中的值來查找兩個迭代之間的差異
set([1,2,3])-set([1,2,4]) # [3]
16.輸出差異
以下方法利用已有函數(shù),尋找并輸出兩個列表之間的差異。
def difference_by(a, b, fn):
b = set(map(fn, b))
return [item for item in a if fn(item) not in b]
from math import floor
difference_by([2.1, 1.2], [2.3, 3.4],floor) # [1.2]
difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x']) # [ { x: 2 } ]
17.鏈?zhǔn)胶瘮?shù)調(diào)用
以下方法可以實(shí)現(xiàn)在一行中調(diào)用多個函數(shù)
def add(a, b):
return a + b
def subtract(a, b):
return a – b
a, b = 4, 5
print((subtract if a > b else add)(a, b)) # 9
18.
在Python3.5及升級版中,也可按下列方式執(zhí)行步驟代碼:
def merge_dictionaries(a, b):
return {**a, **b}
a = { 'x': 1, 'y': 2}
b = { 'y': 3, 'z': 4}
print(merge_dictionaries(a, b)) # {'y': 3, 'x': 1, 'z': 4}
19.將兩個列表轉(zhuǎn)換為字庫
以下方法可將兩個列表轉(zhuǎn)換為字庫。
keys = ["a", "b", "c"]
values = [2, 3, 4]
print(dict(zip(keys, values))) # {'a': 2, 'c': 4, 'b': 3}
20.出現(xiàn)頻率最高的元素
此方法將輸出列表中出鏡率最高的元素。
def most_frequent(list):
return max(set(list), key = list.count)
list = [1,2,1,2,3,2,1,4,2]
most_frequent(list)
21.回文(正反讀有一樣的字符串)
以下代碼檢查給定字符串是否為回文。首先將字符串轉(zhuǎn)換為小寫,然后從中刪除非字母字符,最后將新字符串版本與原版本進(jìn)行比對。
def palindrome(string):
from re import sub
s = sub('[\W_]', '', string.lower())
return s == s[::-1]
palindrome('taco cat') # True
22.不用if-else語句的計算器
以下代碼片段展示了如何在不用if-else條件語句的情況下,編寫簡易計算器。
import operator
action = {
"+": operator.add,
"-": operator.sub,
"/": operator.truediv,
"*": operator.mul,
"**": pow
}
print(action['-'](50, 25)) # 25
23.隨機(jī)排序
該算法采用Fisher-Yates algorithm對新列表中的元素進(jìn)行隨機(jī)排序。
from copy import deepcopy
from random import randint
def shuffle(lst):
temp_lst = deepcopy(lst)
m = len(temp_lst)
while (m):
m -= 1
i = randint(0, m)
temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m]
return temp_lst
foo = [1, 2, 3]
shuffle(foo) # [2,3,1] , foo = [1,2,3]
24.展開列表
此方法只能展開2層嵌套列表,超過2層不行的
def spread(arg):
ret = []
for i in arg:
if isinstance(i, list):
ret.extend(i)
else:
ret.append(i)
return ret
spread([1, 2, 3, [4, 5, 6], [7], 8, 9]) # [1,2,3,4,5,6,7,8,9]
print(spread([1, 2, 3, [4, 5,[10,11,12,132,4,[1,2,3,4,5,6]], 6], [7], 8, 9])) #[1, 2, 3, 4, 5, [10, 11, 12, 132, 4, [1, 2, 3, 4, 5, 6]], 6, 7, 8, 9]
到此這篇關(guān)于分享一些非常實(shí)用的Python小技巧的文章就介紹到這了,更多相關(guān)Python實(shí)用小技巧內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Anaconda安裝pytorch及配置PyCharm 2021環(huán)境
小編使用的是python3.8版本,為了防止訪問量過大導(dǎo)致http連接失敗,所以采用本地安裝,具體安裝方法本文給大家詳細(xì)介紹,在文章底部給大家提到了PyCharm 2021配置環(huán)境的方法,感興趣的朋友一起看看吧2021-06-06
利用Python和OpenCV庫將URL轉(zhuǎn)換為OpenCV格式的方法
這篇文章主要介紹了利用Python和OpenCV庫將URL轉(zhuǎn)換為OpenCV格式的方法,同時用到了NumPy和urllib,需要的朋友可以參考下2015-03-03
python pip配置國內(nèi)鏡像源的方法(永久和臨時)
在使用 pip 安裝 Python 模塊時,默認(rèn)的國外鏡像源可能會導(dǎo)致下載速度緩慢甚至超時,為了解決這個問題,可以使用國內(nèi)的鏡像源來加速下載,以下是常用的國內(nèi)鏡像源以及臨時和永久的配置方法,需要的朋友可以參考下2025-04-04
Python?pygame項(xiàng)目實(shí)戰(zhàn)監(jiān)聽退出事件
這篇文章主要介紹了Python?pygame項(xiàng)目實(shí)戰(zhàn)監(jiān)聽退出事件,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-08-08
python基礎(chǔ)教程之分支、循環(huán)簡單用法
這篇文章主要介紹了python基礎(chǔ)教程之分支、循環(huán)簡單用法,結(jié)合實(shí)例形式分析了Python分支及循環(huán)語句的簡單使用方法,需要的朋友可以參考下2016-06-06
利用Python+Opencv實(shí)現(xiàn)車牌自動識別完整代碼
這篇文章主要介紹了如何使用Python和OpenCV進(jìn)行車牌識別,包括圖像預(yù)處理、車牌定位、分割和模板匹配等步驟,通過實(shí)戰(zhàn)項(xiàng)目,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2025-04-04

