加入收藏 | 设为首页 | 会员中心 | 我要投稿 西安站长网 (https://www.029zz.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 建站 > 正文

30秒内便能学会的30个超实用Python代码片段

发布时间:2019-10-13 07:34:26 所属栏目:建站 来源:读芯术
导读:副标题#e# 许多人在数据科学、机器学习、web开发、脚本编写和自动化等领域中都会使用Python,它是一种十分流行的语言。 Python流行的部分原因在于简单易学。 本文将简要介绍30个简短的、且能在30秒内掌握的代码片段。 1. 唯一性 以下方法可以检查给定列表是

以下方法可将两个字库合并。

  1. def merge_two_dicts(a, b): 
  2.  c = a.copy() # make a copy of a  
  3.  c.update(b) # modify keys and values of a with the ones from b 
  4.  return c 
  5. a = { 'x': 1, 'y': 2} 
  6. b = { 'y': 3, 'z': 4} 
  7. print(merge_two_dicts(a, b)) # {'y': 3, 'x': 1, 'z': 4} 

在Python3.5及升级版中,也可按下列方式执行步骤代码:

  1. def merge_dictionaries(a, b) 
  2.  return {**a, **b} 
  3. a = { 'x': 1, 'y': 2} 
  4. b = { 'y': 3, 'z': 4} 
  5. print(merge_dictionaries(a, b)) # {'y': 3, 'x': 1, 'z': 4} 

20. 将两个列表转换为字库

以下方法可将两个列表转换为字库。

  1. def to_dictionary(keys, values): 
  2.  return dict(zip(keys, values)) 
  3. keys = ["a", "b", "c"]  
  4. values = [2, 3, 4] 
  5. print(to_dictionary(keys, values)) # {'a': 2, 'c': 4, 'b': 3} 

21. 列举

以下代码段可以采用列举的方式来获取列表的值和索引。

  1. list = ["a", "b", "c", "d"] 
  2. for index, element in enumerate(list):  
  3.  print("Value", element, "Index ", index, ) 
  4. # ('Value', 'a', 'Index ', 0) 
  5. # ('Value', 'b', 'Index ', 1) 
  6. #('Value', 'c', 'Index ', 2) 
  7. # ('Value', 'd', 'Index ', 3)  

22. 时间成本

(编辑:西安站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读