总结
豆包 AI 助手文章总结

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

Tomorin
发布: 2018-08-23 17:47:46
原创
2256人浏览过

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

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

交换变量值

"""pythonic way of value swapping"""
a, b=5,10
print(a,b)
a,b=b,a
print(a,b)
登录后复制

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

立即学习Python免费学习笔记(深入)”;

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 Counter
cnt=Counter(a)
print(cnt.most_commin(3))
登录后复制

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

from collections import Counter
Counter(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  =6
print(4< b < 7 )
print(1 == b < 20)
登录后复制

链式函数调用

"""calling different functions with same arguments based on condition"""
def  product(a, b):    
    return a * b
def  add(a, b):   
    return a+ b
b =True
print((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: 
  break
else: 
 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 OrderedDict
items = ["foo", "bar", "bar", "foo"]
print( list( orderedDict.f romkeys(items ).keys( )))
登录后复制

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


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

python速学教程(入门到精通)
python速学教程(入门到精通)

python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
豆包 AI 助手文章总结
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号