溫馨提示×

溫馨提示×

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

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

超實(shí)用Python代碼片段示例

發(fā)布時(shí)間:2021-04-27 12:42:12 來源:億速云 閱讀:158 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要介紹了超實(shí)用Python代碼片段示例,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

python的數(shù)據(jù)類型有哪些?

python的數(shù)據(jù)類型:1. 數(shù)字類型,包括int(整型)、long(長整型)和float(浮點(diǎn)型)。2.字符串,分別是str類型和unicode類型。3.布爾型,Python布爾類型也是用于邏輯運(yùn)算,有兩個(gè)值:True(真)和False(假)。4.列表,列表是Python中使用最頻繁的數(shù)據(jù)類型,集合中可以放任何數(shù)據(jù)類型。5. 元組,元組用”()”標(biāo)識,內(nèi)部元素用逗號隔開。6. 字典,字典是一種鍵值對的集合。7. 集合,集合是一個(gè)無序的、不重復(fù)的數(shù)據(jù)組合。

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

本文將簡要介紹30個(gè)簡短的、且能在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)存

此代碼段可用于檢查對象的內(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次字符串

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

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

6. 首字母大寫

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

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)奖容^

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

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

11. 逗號分隔

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

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. 首字母小寫

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

def decapitalize(string):
   return str[:1].lower() + str[1:]
decapitalize('FooBar') # 'fooBar'
decapitalize('FooBar') # '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]

15. 尋找差異

此方法僅保留第一個(gè)迭代中的值來查找兩個(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 – b
a, b = 4, 5
print((subtract if a > b else add)(a, b)) # 9

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

以下方法利用set()只包含唯一元素的特性來檢查列表是否存在重復(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. 合并字庫

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

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及升級版中,也可按下列方式執(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)換為字庫

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

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. 列舉

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

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語句

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

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)換為小寫,然后從中刪除非字母字符,最后將新字符串版本與原版本進(jìn)行比對。

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

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

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

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

27. 隨機(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]

28. 展開列表

此方法將類似javascript中[].concat(…arr)這樣的列表展開。

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)值

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

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

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“超實(shí)用Python代碼片段示例”這篇文章對大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!

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

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

AI