Python 必知的20個神操作,完美詮釋其簡潔、優美的初衷(初學者必讀)

Python 是一個解釋型語言,可讀性與易用性讓它越來越熱門。

正如 Python 之禪中所述:優美勝於醜陋,明瞭勝於晦澀。

在你的日常編碼中,以下技巧可以給你帶來意想不到的收穫:

1、字符串反轉

下面的代碼片段,使用 Python 中 slicing 操作,來實現字符串反轉:

# Reversing a string using slicing

my_string = "ABCDE"
reversed_string = my_string[::-1]

print(reversed_string)

# Output
# EDCBA

2、首字母大寫

下面的代碼片段,可以將字符串進行首字母大寫,使用的是 String 類的 title() 方法:

my_string = "my name is chaitanya baweja"

# using the title() function of string class
new_string = my_string.title()

print(new_string)

# Output
# My Name Is Chaitanya Baweja

03、取組成字符串的元素

下面的代碼片段,可以用來找出一個字符串中所有組成他的元素,我們使用的是 set 中只能存儲不重複的元素 這一特性:

 my_string = "aavvccccddddeee"
 
 # converting the string to a set
 temp_set = set(my_string)
 
 # stitching set into a string using join
 new_string = ''.join(temp_set)
 
 print(new_string)

# Output
# acedv

04、重複輸出String/List

可以對 String/List 進行乘法運算,這個方法,可以使用它們任意倍增。

n = 3 # number of repetitions
my_string = "abcd"
my_list = [1,2,3]

print(my_string*n)
# abcdabcdabcd

print(my_string*n)
# [1,2,3,1,2,3,1,2,3]

有一個很有意思的用法,定義包含n個常量的列表:

n = 4
my_list = [0]*n # n 表示所需列表的長度
# [0, 0, 0, 0]

05、列表推導式

列表推導式提供了一種更優雅的方式處理列表。

以下代碼片段中,將舊列表中的元素乘以2來創建新的列表:

original_list = [1,2,3,4]

new_list = [2*x for x in original_list]

print(new_list)
# [2,4,6,8]

06、交換兩個變量值

Python 交換兩個變量的值不需要創建一箇中間變量,很簡單就可以實現:

a = 1
b = 2

a, b = b, a

print(a) # 2
print(b) # 1

07、字符串拆分

使用 split() 方法可以將一個字符串拆分成多個子串,你也可以將分割符作爲參數傳遞進行,進行分割。

 string_1 = "My name is Chaitanya Baweja"
 string_2 = "sample/ string 2"
 
 # default separator ' '
 print(string_1.split())
 # ['My', 'name', 'is', 'Chaitanya', 'Baweja']
 
 # defining separator as '/'
 print(string_2.split('/'))
# ['sample', ' string 2']

08、字符串拼接

join()方法可以將字符串列表組合成一個字符串,下面的代碼片段中,我使用,將所有的字符串拼接到一起:

list_of_strings = ['My', 'name', 'is', 'Chaitanya', 'Baweja']

# Using join with the comma separator
print(','.join(list_of_strings))

# Output
# My,name,is,Chaitanya,Baweja

09、迴文檢測

在前面,我們已經說過了,如何翻轉一個字符串,所以迴文檢測非常的簡單:

my_string = "abcba"

if my_string == my_string[::-1]:
    print("palindrome")
else:
   print("not palindrome")

# Output
# palindrome

10、元素重複次數

在Python中,有很多方法可以做這件事情,但是我最喜歡的還是 Counter 這個類。

Counter會計算每一個元素出現的次數,Counter()會返回一個字典,元素作爲key,出現的次數作爲 value。

我們也可以使用 most_common() 這個方法來獲取出現字數最多的元素。

 from collections import Counter
 
 my_list = ['a','a','b','b','b','c','d','d','d','d','d']
 count = Counter(my_list) # defining a counter object
 
 print(count) # Of all elements
 # Counter({'d': 5, 'b': 3, 'a': 2, 'c': 1})
 
 print(count['b']) # of individual element
 # 3

 print(count.most_common(1)) # most frequent element
 # [('d', 5)]

11、變位詞

使用Counter的一個很有意思的用法是找變位詞:

變位詞一種把某個詞或句子的字母的位置(順序)加以改換所形成的新詞。

使用 Counter 得到的兩個對象如果相等,則他們是變位詞:

from collections import Counter

str_1, str_2, str_3 = "acbde", "abced", "abcda"
cnt_1, cnt_2, cnt_3  = Counter(str_1), Counter(str_2), Counter(str_3)

if cnt_1 == cnt_2:
    print('1 and 2 anagram')
if cnt_1 == cnt_3:
    print('1 and 3 anagram')

12、try-except-else

在Python中,使用 try-except 進行異常捕獲。else 可用於當沒有異常發生時執行。
如果你需要執行一些代碼,不管是否發生過異常,請使用 final:

 a, b = 1,0
 
 try:
     print(a/b)
     # exception raised when b is 0
 6except ZeroDivisionError:
     print("division by zero")
 8else:
     print("no exceptions raised")
 finally:
     print("Run this always")

13、枚舉遍歷

下面的代碼片段中,遍歷列表中的值和對應的索引:

 my_list = ['a', 'b', 'c', 'd', 'e']
 
 for index, value in enumerate(my_list):
     print('{0}: {1}'.format(index, value))
 
 # 0: a
 # 1: b
 # 2: c
 # 3: d
 # 4: e

14、對象使用內存大小

下面的代碼片段展示了,如何獲取一個對象所佔用的內存大小:

import sys

num = 21

print(sys.getsizeof(num))

# In Python 2, 24
# In Python 3, 28

15、合併兩個字典

在 Python 2 中,使用 update() 方法來合併,在 Python 3.5 中,更加簡單,在下面的代碼片段中,合併了兩個字典,在兩個字典存在交集的時候,則使用後一個進行覆蓋。

dict_1 = {'apple': 9, 'banana': 6}
dict_2 = {'banana': 4, 'orange': 8}

combined_dict = {**dict_1, **dict_2}

print(combined_dict)
# Output
# {'apple': 9, 'banana': 4, 'orange': 8}

16、代碼執行時間

下面的代碼片段中,使用了 time 這個庫,來計算代碼執行的時間:

 import time
 
 start_time = time.time()
 # Code to check follows
 a, b = 1,2
 c = a+ b
 # Code to check ends
 end_time = time.time()
 time_taken_in_micro = (end_time- start_time)*(10**6)

 print(" Time taken in micro_seconds: {0} ms").format(time_taken_in_micro)

17、列表展開

有時候,你不知道你當前列表的嵌套深度,但是你希望把他們展開,放到一維的列表中。下面教你實現它:

 from iteration_utilities import deepflatten
 
 # if you only have one depth nested_list, use this
 def flatten(l):
   return [item for sublist in l for item in sublist]
 
 l = [[1,2,3],[3]]
 print(flatten(l))
 # [1, 2, 3, 3]

 # if you don't know how deep the list is nested
 l = [[1,2,3],[4,[5],[6,7]],[8,[9,[10]]]]

 print(list(deepflatten(l, depth=3)))
 # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

18、隨機取樣

下面的例子中,使用 random 庫,實現了從列表中隨機取樣。

import random

my_list = ['a', 'b', 'c', 'd', 'e']
num_samples = 2

samples = random.sample(my_list,num_samples)
print(samples)

隨機取樣,我推薦使用 secrets 庫來實現,更安全。下面的代碼片段只能在 Python 3 中運行:

import secrets                              # imports secure module.
secure_random = secrets.SystemRandom()      # creates a secure random object.

my_list = ['a','b','c','d','e']
num_samples = 2

samples = secure_random.sample(my_list, num_samples)

print(samples)

19、數字化

下面代碼將一個整形數轉成一個數字化的對象:

num = 123456

list_of_digits = list(map(int, str(num)))

print(list_of_digits)
# [1, 2, 3, 4, 5, 6]

20、唯一性檢查

下面的代碼示例,可以檢查列表中的元素是否是不重複的:

 def unique(l):
     if len(l)==len(set(l)):
         print("All elements are unique")
     else:
         print("List has duplicates")
 
 unique([1,2,3,4])
 # All elements are unique
 
 unique([1,1,2,3])
 # List has duplicates

 

更多精彩,請關注我的"今日頭條號":Java雲筆記
隨時隨地,讓你擁有最新,最便捷的掌上雲服務

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章