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) )
链式比较
""<span style="color:transparent">本文来源gaodai#ma#com搞*!代#%^码网%</span>" 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))