溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

實(shí)用Python代碼片段分別有哪些

發(fā)布時(shí)間:2021-10-28 17:28:43 來(lái)源:億速云 閱讀:190 作者:柒染 欄目:編程語(yǔ)言

實(shí)用Python代碼片段分別有哪些,針對(duì)這個(gè)問(wèn)題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問(wèn)題的小伙伴找到更簡(jiǎn)單易行的方法。

許多人在數(shù)據(jù)科學(xué)、機(jī)器學(xué)習(xí)、web開(kāi)發(fā)、腳本編寫(xiě)和自動(dòng)化等領(lǐng)域中都會(huì)使用Python,它是一種十分流行的語(yǔ)言。

實(shí)用Python代碼片段分別有哪些

Python流行的部分原因在于簡(jiǎn)單易學(xué)。

本文將簡(jiǎn)要介紹30個(gè)簡(jiǎn)短的、且能在30秒內(nèi)掌握的代碼片段。

1. 唯一性

以下方法可以檢查給定列表是否有重復(fù)的地方,可用set()的屬性將其從列表中刪除。

def all_unique(lst):  return len(lst) == len(set(lst)) x = [1,1,2,2,3,2,3,4,5,6] y = [1,2,3,4,5] all_unique(x) # False all_unique(y) # True

2. 變位詞(相同字母異序詞)

此方法可用于檢查兩個(gè)字符串是否為變位詞。

from collections import Counter def anagram(first, second):  return Counter(first) == Counter(second) anagram("abcd3", "3acdb") # True

3. 內(nèi)存

此代碼段可用于檢查對(duì)象的內(nèi)存使用情況。

import sys  variable = 30  print(sys.getsizeof(variable)) # 24

4. 字節(jié)大小

此方法可輸出字符串的字節(jié)大小。

def byte_size(string):  return(len(string.encode('utf-8'))) byte_size('') # 4 byte_size('Hello World') # 11

5. 打印N次字符串

此代碼段無(wú)需經(jīng)過(guò)循環(huán)操作便可多次打印字符串。

n = 2;  s ="Programming";  print(s * n); # ProgrammingProgramming

6. 首字母大寫(xiě)

以下代碼片段只利用了title(),就能將字符串中每個(gè)單詞的首字母大寫(xiě)。

s = "programming is awesome" print(s.title()) # Programming Is Awesome

7. 列表細(xì)分

該方法將列表細(xì)分為特定大小的列表。

def chunk(list, size):  return [list[i:i+size] for i in range(0,len(list), size)]

8. 壓縮

以下代碼使用filter()從,將錯(cuò)誤值(False、None、0和“ ”)從列表中刪除。

def compact(lst):  return list(filter(bool, lst)) compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ]

9. 計(jì)數(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)奖容^

以下代碼可對(duì)各種運(yùn)算符進(jìn)行多次比較。

a = 3 print( 2 < a < 8) # True print(1 == a < 2) # False

11. 逗號(hào)分隔

此代碼段可將字符串列表轉(zhuǎn)換為單個(gè)字符串,同時(shí)將列表中的每個(gè)元素用逗號(hào)隔開(kāi)。

hobbies = ["basketball", "football", "swimming"] print("My hobbies are: " + ", ".join(hobbies)) # My hobbies are: basketball, football, swimming

12. 元音計(jì)數(shù)

此方法可計(jì)算字符串中元音(“a”、“e”、“i”、“o”、“u”)的數(shù)目。

import re def count_vowels(str):  return len(len(re.findall(r'[aeiou]', str, re.IGNORECASE)) count_vowels('foobar') # 3 count_vowels('gym') # 0

13. 首字母小寫(xiě)

此方法可將給定字符串的首字母轉(zhuǎn)換為小寫(xiě)模式。

def decapitalize(string):  return str[:1].lower() + str[1:]   decapitalize('FooBar') # 'fooBar' decapitalize('FooBar') # 'fooBar'

14. 展開(kāi)列表

下列代碼采用了遞歸法展開(kāi)潛在的深層列表。

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]

15. 尋找差異

此方法僅保留第一個(gè)迭代中的值來(lái)查找兩個(gè)迭代之間的差異。

def difference(a, b):  set_a = set(a)  set_b = set(b)  comparison = set_a.difference(set_b)  return list(comparison) difference([1,2,3], [1,2,4]) # [3]

16. 輸出差異

以下方法利用已有函數(shù),尋找并輸出兩個(gè)列表之間的差異。

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)用多個(gè)函數(shù)。

def add(a, b):  return a + b def subtract(a, b):  return a &ndash; b a, b = 4, 5 print((subtract if a > b else add)(a, b)) # 9

18. 重復(fù)值存在與否

以下方法利用set()只包含唯一元素的特性來(lái)檢查列表是否存在重復(fù)值。

def has_duplicates(lst):  return len(lst) != len(set(lst)) x = [1,2,3,4,5,5] y = [1,2,3,4,5] has_duplicates(x) # True has_duplicates(y) # False

19. 合并字庫(kù)

以下方法可將兩個(gè)字庫(kù)合并。

def merge_two_dicts(a, b):  c = a.copy() # make a copy of a   c.update(b) # modify keys and values of a with the ones from b  return c a = { 'x': 1, 'y': 2} b = { 'y': 3, 'z': 4} print(merge_two_dicts(a, b)) # {'y': 3, 'x': 1, 'z': 4}

在Python3.5及升級(jí)版中,也可按下列方式執(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}

20. 將兩個(gè)列表轉(zhuǎn)換為字庫(kù)

以下方法可將兩個(gè)列表轉(zhuǎn)換為字庫(kù)。

def to_dictionary(keys, values):  return dict(zip(keys, values)) keys = ["a", "b", "c"]  values = [2, 3, 4] print(to_dictionary(keys, values)) # {'a': 2, 'c': 4, 'b': 3}

21. 列舉

以下代碼段可以采用列舉的方式來(lái)獲取列表的值和索引。

list = ["a", "b", "c", "d"] for index, element in enumerate(list):   print("Value", element, "Index ", index, ) # ('Value', 'a', 'Index ', 0) # ('Value', 'b', 'Index ', 1) #('Value', 'c', 'Index ', 2) # ('Value', 'd', 'Index ', 3)

22. 時(shí)間成本

以下代碼可計(jì)算執(zhí)行特定代碼所需的時(shí)間。

import time start_time = time.time() a = 1 b = 2 c = a + b print(c) #3 end_time = time.time() total_time = end_time - start_time print("Time: ", total_time) # ('Time: ', 1.1205673217773438e-05)

23. Try else語(yǔ)句

可將else句作為try/except語(yǔ)句的一部分,如果沒(méi)有異常情況,則執(zhí)行else語(yǔ)句。

try:  2*3 except TypeError:  print("An exception was raised") else:  print("Thank God, no exceptions were raised.") #Thank God, no exceptions were raised.

24. 出現(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)

25. 回文(正反讀有一樣的字符串)

以下代碼檢查給定字符串是否為回文。首先將字符串轉(zhuǎn)換為小寫(xiě),然后從中刪除非字母字符,最后將新字符串版本與原版本進(jìn)行比對(duì)。

def palindrome(string):  from re import sub  s = sub('[\W_]', '', string.lower())  return s == s[::-1] palindrome('taco cat') # True

26. 不用if-else語(yǔ)句的計(jì)算器

以下代碼片段展示了如何在不用if-else條件語(yǔ)句的情況下,編寫(xiě)簡(jiǎn)易計(jì)算器。

import operator action = {  "+": operator.add,  "-": operator.sub,  "/": operator.truediv,  "*": operator.mul,  "**": pow } print(action['-'](50, 25)) # 25

27. 隨機(jī)排序

該算法采用Fisher-Yates algorithm對(duì)新列表中的元素進(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]

28. 展開(kāi)列表

此方法將類(lèi)似javascript中[].concat(&hellip;arr)這樣的列表展開(kāi)。

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]

29. 交換變量

此方法為能在不使用額外變量的情況下快速交換兩種變量。

def swap(a, b):  return b, a a, b = -1, 14 swap(a, b) # (14, -1)

30. 獲取丟失部分的默認(rèn)值

以下代碼可在所需對(duì)象不在字庫(kù)范圍內(nèi)的情況下獲取默認(rèn)值。

d = {'a': 1, 'b': 2} print(d.get('c', 3)) # 3

這里只簡(jiǎn)單介紹了一些能在日常工作中幫到我們的方法。

關(guān)于實(shí)用Python代碼片段分別有哪些問(wèn)題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒(méi)有解開(kāi),可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI