Python 是一個(gè)解釋型語言,可讀性與易用性讓它越來越熱門。
正如 Python 之禪中所述:
優(yōu)美勝于丑陋,明了勝于晦澀。
在你的日常編碼中,以下技巧可以給你帶來意想不到的收獲。
字符串反轉(zhuǎn)
下面的代碼片段,使用 Python 中 slicing 操作,來實(shí)現(xiàn)字符串反轉(zhuǎn):
1# Reversing a string using slicing
2
3my_string = 'ABCDE'
4reversed_string = my_string[::-1]
5
6print(reversed_string)
7
8# Output
9# EDCBA
在這篇文章(https://medium.com/swlh/how-to-reverse-a-string-in-python-66fc4bbc7379)中,你可以了解更多細(xì)節(jié)。
首字母大寫
下面的代碼片段,可以將字符串進(jìn)行首字母大寫,使用的是 String 類的 title()
方法:
1my_string = 'my name is chaitanya baweja'
2
3# using the title() function of string class
4new_string = my_string.title()
5
6print(new_string)
7
8# Output
9# My Name Is Chaitanya Baweja
下面的代碼片段,可以用來找出一個(gè)字符串中所有組成他的元素,我們使用的是 set 中只能存儲(chǔ)不重復(fù)的元素 這一特性:
1my_string = 'aavvccccddddeee'
2
3# converting the string to a set
4temp_set = set(my_string)
5
6# stitching set into a string using join
7new_string = ''.join(temp_set)
8
9print(new_string)
10
11# Output
12# acedv
可以對(duì) String/List 進(jìn)行乘法運(yùn)算,這個(gè)方法,可以使用它們?nèi)我獗对觥?/p>
1n = 3 # number of repetitions
2my_string = 'abcd'
3my_list = [1,2,3]
4
5print(my_string*n)
6# abcdabcdabcd
7
8print(my_string*n)
9# [1,2,3,1,2,3,1,2,3]
有一個(gè)很有意思的用法,定義包含n個(gè)常量的列表:
1n = 4
2my_list = [0]*n # n 表示所需列表的長(zhǎng)度
3# [0, 0, 0, 0]
列表推導(dǎo)式提供了一種更優(yōu)雅的方式處理列表。
以下代碼片段中,將舊列表中的元素乘以2來創(chuàng)建新的列表:
1original_list = [1,2,3,4]
2
3new_list = [2*x for x in original_list]
4
5print(new_list)
6# [2,4,6,8]
Python 交換兩個(gè)變量的值不需要?jiǎng)?chuàng)建一個(gè)中間變量,很簡(jiǎn)單就可以實(shí)現(xiàn):
1a = 1
2b = 2
3
4a, b = b, a
5
6print(a) # 2
7print(b) # 1
使用 split()
方法可以將一個(gè)字符串拆分成多個(gè)子串,你也可以將分割符作為參數(shù)傳遞進(jìn)行,進(jìn)行分割。
1string_1 = 'My name is Chaitanya Baweja'
2string_2 = 'sample/ string 2'
3
4# default separator ' '
5print(string_1.split())
6# ['My', 'name', 'is', 'Chaitanya', 'Baweja']
7
8# defining separator as '/'
9print(string_2.split('/'))
10# ['sample', ' string 2']
join()
方法可以將字符串列表組合成一個(gè)字符串,下面的代碼片段中,我使用,
將所有的字符串拼接到一起:
1list_of_strings = ['My', 'name', 'is', 'Chaitanya', 'Baweja']
2
3# Using join with the comma separator
4print(','.join(list_of_strings))
5
6# Output
7# My,name,is,Chaitanya,Baweja
在前面,我們已經(jīng)說過了,如何翻轉(zhuǎn)一個(gè)字符串,所以回文檢測(cè)非常的簡(jiǎn)單:
1my_string = 'abcba'
2
3if my_string == my_string[::-1]:
4 print('palindrome')
5else:
6 print('not palindrome')
7
8# Output
9# palindrome
在Python中,有很多方法可以做這件事情,但是我最喜歡的還是 Counter
這個(gè)類。
Counter
會(huì)計(jì)算每一個(gè)元素出現(xiàn)的次數(shù),Counter()
會(huì)返回一個(gè)字典,元素作為key,出現(xiàn)的次數(shù)作為 value。
我們也可以使用 most_common()
這個(gè)方法來獲取出現(xiàn)字?jǐn)?shù)最多的元素。
1from collections import Counter
2
3my_list = ['a','a','b','b','b','c','d','d','d','d','d']
4count = Counter(my_list) # defining a counter object
5
6print(count) # Of all elements
7# Counter({'d': 5, 'b': 3, 'a': 2, 'c': 1})
8
9print(count['b']) # of individual element
10# 3
11
12print(count.most_common(1)) # most frequent element
13# [('d', 5)]
使用Counter
的一個(gè)很有意思的用法是找變位詞:
變位詞一種把某個(gè)詞或句子的字母的位置(順序)加以改換所形成的新詞。
使用 Counter
得到的兩個(gè)對(duì)象如果相等,則他們是變位詞:
1from collections import Counter
2
3str_1, str_2, str_3 = 'acbde', 'abced', 'abcda'
4cnt_1, cnt_2, cnt_3 = Counter(str_1), Counter(str_2), Counter(str_3)
5
6if cnt_1 == cnt_2:
7 print('1 and 2 anagram')
8if cnt_1 == cnt_3:
9 print('1 and 3 anagram')
1my_list = ['a', 'b', 'c', 'd', 'e']
2
3for index, value in enumerate(my_list):
4 print('{0}: {1}'.format(index, value))
5
6# 0: a
7# 1: b
8# 2: c
9# 3: d
10# 4: e
update()
方法來合并,在 Python 3.5 中,更加簡(jiǎn)單,在下面的代碼片段中,合并了兩個(gè)字典,在兩個(gè)字典存在交集的時(shí)候,則使用后一個(gè)進(jìn)行覆蓋。1dict_1 = {'apple': 9, 'banana': 6}
2dict_2 = {'banana': 4, 'orange': 8}
3
4combined_dict = {**dict_1, **dict_2}
5
6print(combined_dict)
7# Output
8# {'apple': 9, 'banana': 4, 'orange': 8}
下面的代碼片段中,使用了 time
這個(gè)庫,來計(jì)算代碼執(zhí)行的時(shí)間:
1import time
2
3start_time = time.time()
4# Code to check follows
5a, b = 1,2
6c = a+ b
7# Code to check ends
8end_time = time.time()
9time_taken_in_micro = (end_time- start_time)*(10**6)
10
11print(' Time taken in micro_seconds: {0} ms').format(time_taken_in_micro)
有時(shí)候,你不知道你當(dāng)前列表的嵌套深度,但是你希望把他們展開,放到一維的列表中。下面教你實(shí)現(xiàn)它:
1from iteration_utilities import deepflatten
2
3# if you only have one depth nested_list, use this
4def flatten(l):
5 return [item for sublist in l for item in sublist]
6
7l = [[1,2,3],[3]]
8print(flatten(l))
9# [1, 2, 3, 3]
10
11# if you don't know how deep the list is nested
12l = [[1,2,3],[4,[5],[6,7]],[8,[9,[10]]]]
13
14print(list(deepflatten(l, depth=3)))
15# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Numpy flatten 可以更好的處理你格式化好的數(shù)據(jù)。
下面的例子中,使用 random
庫,實(shí)現(xiàn)了從列表中隨機(jī)取樣。
1import random
2
3my_list = ['a', 'b', 'c', 'd', 'e']
4num_samples = 2
5
6samples = random.sample(my_list,num_samples)
7print(samples)
隨機(jī)取樣,我推薦使用 secrets
庫來實(shí)現(xiàn),更安全。下面的代碼片段只能在 Python 3 中運(yùn)行:
1import secrets # imports secure module.
2secure_random = secrets.SystemRandom() # creates a secure random object.
3
4my_list = ['a','b','c','d','e']
5num_samples = 2
6
7samples = secure_random.sample(my_list, num_samples)
8
9print(samples)
下面代碼將一個(gè)整形數(shù)轉(zhuǎn)成一個(gè)數(shù)字化的對(duì)象:
1num = 123456
2
3list_of_digits = list(map(int, str(num)))
4
5print(list_of_digits)
6# [1, 2, 3, 4, 5, 6]
下面的代碼示例,可以檢查列表中的元素是否是不重復(fù)的:
1def unique(l):
2 if len(l)==len(set(l)):
3 print('All elements are unique')
4 else:
5 print('List has duplicates')
6
7unique([1,2,3,4])
8# All elements are unique
9
10unique([1,1,2,3])
11# List has duplicates
這些是我在日常工作中發(fā)掘出來非常有用的代碼。非常感謝閱讀本文,希望對(duì)你有幫助。
聯(lián)系客服