当前位置:Gxlcms > Python > Python学习之17个关于Python的小技巧

Python学习之17个关于Python的小技巧

时间:2021-07-01 10:21:17 帮助过:107人阅读

Python 是一门非常简洁的语言,python的简洁易用令人不得不感叹这门语言的轻便。在本文中,我们列举了 17 个非常有用的 Python 技巧,这 17 个技巧都非常简单,但它们都很常用且能激发不一样的思路。

很多人都知道 Python 是一种高级编程语言,其设计的核心理念是代码的易读性,以及允许编程者通过若干行代码轻松表达想法创意。实际上,很多人选择学习 Python 的首要原因是其编程的优美性,用它编码和表达想法非常自然。此外,Python编写使用方式有多种,数据科学、网页开发、机器学习皆可使用 Python。Quora、Pinterest 和 Spotify 都使用 Python 作为其后端开发语言。

交换变量值

  1. """pythonic way of value swapping"""
  2. a, b=5,10
  3. print(a,b)
  4. a,b=b,a
  5. print(a,b)

将列表中的所有元素组合成字符串

  1. a=["python","is","awesome"]
  2. print(" ".join(a))

查找列表中频率最高的值

  1. """most frequent element in a list"""
  2. a=[1,2,3,1,2,3,2,2,4,5,1]
  3. print(max(set(a),key=a.count))
  4. """using Counter from collections"""
  5. from collections import Counter
  6. cnt=Counter(a)
  7. print(cnt.most_commin(3))

检查两个字符串是不是由相同字母不同顺序组成


  1. from collections import Counter
  2. Counter(str1)==Counter(str2)

反转字符串


  1. """reversing string with special case of slice step param"""
  2. a ='abcdefghij k lmnopqrs tuvwxyz 'print(a[ ::-1] )
  3. """iterating over string contents in reverse efficiently."""
  4. for char in reversed(a):
  5. print(char )
  6. """reversing an integer through type conversion and slicing ."""
  7. num = 123456789
  8. print( int( str(num)[::1]))

反转列表


  1. """reversing list with special case of slice step param"""
  2. a=[5,4,3,2,1]
  3. print(a[::1])
  4. """iterating over list contents in reverse efficiently ."""
  5. for ele in reversed(a):
  6. print(ele )

转置二维数组

  1. """transpose 2d array [[a,b], [c,d], [e,f]] -> [[a,c,e], [b,d,f]]"""
  2. original = [['a', 'b'], ['c', 'd'], ['e', 'f']]
  3. transposed = zip( *original )
  4. print(list( transposed) )

链式比较


  1. """ chained comparison with all kind of operators"""
  2. b =6
  3. print(4< b < 7 )
  4. print(1 == b < 20)

链式函数调用

  1. """calling different functions with same arguments based on condition"""
  2. def product(a, b):
  3. return a * b
  4. def add(a, b):
  5. return a+ b
  6. b =True
  7. print((product if b else add)(5, 7))

复制列表


  1. """a fast way to make a shallow copy of a list"""
  2. b=a
  3. b[0]= 10
  4. """ bothaandbwillbe[10,2,3,4,5]"""
  5. b = a[:]b[O] = 10
  6. """only b will change to [10, 2, 3, 4, 5] """
  7. """copy list by typecasting method"""
  8. a=[l,2,3,4,5]
  9. print(list(a))
  10. """using the list.copy( ) method ( python3 only )"""
  11. a=[1,2,3,4,5]
  12. print(a.copy( ))
  13. """copy nested lists using copy. deepcopy"""
  14. from copy import deepcopy
  15. l=[l,2],[3,4]]
  16. l2 = deepcopy(l)
  17. print(l2)

字典get法


  1. """ returning None or default value, when key is not in dict"""
  2. d = ['a': 1, 'b': 2]
  3. print(d.get('c', 3))

通过「键」排序字典元素


  1. """Sort a dictionary by its values with the built-in sorted( ) function and a ' key' argument ."""
  2. d = {'apple': 10, 'orange': 20, ' banana': 5, 'rotten tomato': 1)
  3. print( sorted(d. items( ), key=lambda x: x[1]))
  4. """Sort using operator . itemgetter as the sort key instead of a lambda"""
  5. from operator import itemgetter
  6. print( sorted(d. items(), key=itemgetter(1)))
  7. """Sort dict keys by value"""
  8. print( sorted(d, key=d.get))

For Else


  1. """else gets called when for loop does not reach break statement"""
  2. a=[1,2,3,4,5]
  3. for el in a:
  4. if el==0:
  5. break
  6. else:
  7. print( 'did not break out of for loop' )

转换列表为逗号分割符格式


  1. """converts list to comma separated string"""
  2. items = [foo', 'bar', 'xyz']
  3. print (','.join( items))
  4. """list of numbers to comma separated"""
  5. numbers = [2, 3, 5, 10]
  6. print (','.join(map(str, numbers)))
  7. """list of mix data"""
  8. data = [2, 'hello', 3, 3,4]
  9. print (','.join(map(str, data)))

合并字典

  1. """merge dict's"""
  2. d1 = {'a': 1}
  3. d2 = {'b': 2}
  4. # python 3.5
  5. print({**d1, **d2})
  6. print(dict(d1. items( ) | d2. items( )))
  7. d1. update(d2)
  8. print(d1)

列表中最小和最大值的索引

  1. """Find Index of Min/Max Element .
  2. """
  3. lst= [40, 10, 20, 30]
  4. def minIndex(lst):
  5. return min( range(len(lst)), key=lst.. getitem__ )
  6. def maxIndex(lst):
  7. return max( range( len(lst)), key=lst.. getitem__ )
  8. print( minIndex(lst))
  9. print( maxIndex(lst))

移除列表中的重复元素


  1. """remove duplicate items from list. note: does, not preserve the original list order"""
  2. items=[2,2,3,3,1]
  3. newitems2 = list(set( items))
  4. print (newitems2)
  5. """remove dups and, keep. order"""
  6. from collections import OrderedDict
  7. items = ["foo", "bar", "bar", "foo"]
  8. print( list( orderedDict.f romkeys(items ).keys( )))

以上,就是关于Python编程中的17个实用且有效的小操作


以上就是Python学习之17个关于Python的小技巧的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行