Python 是一門非常簡潔的語言,
python的簡潔易用令人不得不感歎這門語言的輕便。在本文中,我們列舉了 17 個非常有用的
Python 技巧,這
17 個技巧都非常簡單,但它們都很常用且能激發不一樣的思路。
很多人都知道 Python 是一種進階程式設計語言,其設計的核心理念是代碼的易讀性,以及允許編程者通過若干行代碼輕鬆表達想法創意。實際上,很多人選擇學習 Python 的首要原因是其編程的優美性,用它編碼和表達想法非常自然。此外,Python 的編寫使用方式有多種,資料科學、網頁開發、機器學習皆可使用 Python。Quora、Pinterest 和 Spotify 都使用 Python 作為其後端開發語言。
交換變數值
"""pythonic way of value swapping"""a, b=5,10print(a,b)a,b=b,aprint(a,b)
將列表中的所有元素組合成字串
a=["python","is","awesome"]print(" ".join(a))
尋找列表中頻率最高的值
"""most frequent element in a list"""a=[1,2,3,1,2,3,2,2,4,5,1]print(max(set(a),key=a.count))"""using Counter from collections"""from collections import Countercnt=Counter(a)print(cnt.most_commin(3))
檢查兩個字串是不是由相同字母不同順序組成
from collections import CounterCounter(str1)==Counter(str2)
反轉字串
"""reversing string with special case of slice step param""" a ='abcdefghij k lmnopqrs tuvwxyz 'print(a[ ::-1] ) """iterating over string contents in reverse efficiently.""" for char in reversed(a): print(char ) """reversing an integer through type conversion and slicing .""" num = 123456789 print( int( str(num)[::1]))
反轉列表
"""reversing list with special case of slice step param""" a=[5,4,3,2,1] print(a[::1]) """iterating over list contents in reverse efficiently .""" for ele in reversed(a): print(ele )
轉置二維數組
"""transpose 2d array [[a,b], [c,d], [e,f]] -> [[a,c,e], [b,d,f]]"""original = [['a', 'b'], ['c', 'd'], ['e', 'f']]transposed = zip( *original )print(list( transposed) )
鏈式比較
""" chained comparison with all kind of operators"""b =6print(4< b < 7 )print(1 == b < 20)
鏈式函數調用
"""calling different functions with same arguments based on condition"""def product(a, b): return a * bdef add(a, b): return a+ bb =Trueprint((product if b else add)(5, 7))
複製列表
"""a fast way to make a shallow copy of a list""" b=a b[0]= 10 """ bothaandbwillbe[10,2,3,4,5]""" b = a[:]b[O] = 10 """only b will change to [10, 2, 3, 4, 5] """ """copy list by typecasting method""" a=[l,2,3,4,5]print(list(a)) """using the list.copy( ) method ( python3 only )""" a=[1,2,3,4,5] print(a.copy( )) """copy nested lists using copy. deepcopy""" from copy import deepcopy l=[l,2],[3,4]] l2 = deepcopy(l)print(l2)
字典get法
""" returning None or default value, when key is not in dict""" d = ['a': 1, 'b': 2]print(d.get('c', 3))
通過「鍵」排序字典元素
"""Sort a dictionary by its values with the built-in sorted( ) function and a ' key' argument .""" d = {'apple': 10, 'orange': 20, ' banana': 5, 'rotten tomato': 1) print( sorted(d. items( ), key=lambda x: x[1])) """Sort using operator . itemgetter as the sort key instead of a lambda""" from operator import itemgetter print( sorted(d. items(), key=itemgetter(1))) """Sort dict keys by value""" print( sorted(d, key=d.get))
For Else
"""else gets called when for loop does not reach break statement"""a=[1,2,3,4,5]for el in a: if el==0: breakelse: print( 'did not break out of for loop' )
轉換列表為逗號分割符格式
"""converts list to comma separated string"""items = [foo', 'bar', 'xyz']print (','.join( items))"""list of numbers to comma separated"""numbers = [2, 3, 5, 10]print (','.join(map(str, numbers)))"""list of mix data"""data = [2, 'hello', 3, 3,4]print (','.join(map(str, data)))
合并字典
"""merge dict's"""d1 = {'a': 1}d2 = {'b': 2}# python 3.5 print({**d1, **d2})print(dict(d1. items( ) | d2. items( )))d1. update(d2)print(d1)
列表中最小和最大值的索引
"""Find Index of Min/Max Element ."""lst= [40, 10, 20, 30]def minIndex(lst): return min( range(len(lst)), key=lst.. getitem__ )def maxIndex(lst): return max( range( len(lst)), key=lst.. getitem__ )print( minIndex(lst)) print( maxIndex(lst))
移除列表中的重複元素
"""remove duplicate items from list. note: does, not preserve the original list order"""items=[2,2,3,3,1]newitems2 = list(set( items)) print (newitems2)"""remove dups and, keep. order"""from collections import OrderedDictitems = ["foo", "bar", "bar", "foo"]print( list( orderedDict.f romkeys(items ).keys( )))
以上,就是關於Python編程中的17個實用且有效小操作