| 
                         以下代码可计算执行特定代码所需的时间。 
- import time 
 - start_time = time.time() 
 - a = 1 
 - b = 2 
 - c = a + b 
 - print(c) #3 
 - end_time = time.time() 
 - total_time = end_time - start_time 
 - print("Time: ", total_time) 
 - # ('Time: ', 1.1205673217773438e-05) 
 
  
23. Try else语句 
可将else句作为try/except语句的一部分,如果没有异常情况,则执行else语句。 
- try: 
 -  2*3 
 - except TypeError: 
 -  print("An exception was raised") 
 - else: 
 -  print("Thank God, no exceptions were raised.") 
 - #Thank God, no exceptions were raised. 
 
  
24. 出现频率很高的元素 
此方法将输出列表中出镜率很高的元素。 
- def most_frequent(list): 
 -  return max(set(list), key = list.count) 
 - list = [1,2,1,2,3,2,1,4,2] 
 - most_frequent(list)  
 
  
25. 回文(正反读有一样的字符串) 
以下代码检查给定字符串是否为回文。首先将字符串转换为小写,然后从中删除非字母字符,最后将新字符串版本与原版本进行比对。 
- def palindrome(string): 
 -  from re import sub 
 -  s = sub('[W_]', '', string.lower()) 
 -  return s == s[::-1] 
 - palindrome('taco cat') # True 
 
  
26. 不用if-else语句的计算器 
以下代码片段展示了如何在不用if-else条件语句的情况下,编写简易计算器。 
- import operator 
 - action = { 
 -  "+": operator.add, 
 -  "-": operator.sub, 
 -  "/": operator.truediv, 
 -  "*": operator.mul, 
 -  "**": pow 
 - } 
 - print(action['-'](50, 25)) # 25 
 
  
27. 随机排序 
该算法采用Fisher-Yates algorithm对新列表中的元素进行随机排序。 
- from copy import deepcopy 
 - from random import randint 
 - def shuffle(lst): 
 -  temp_lst = deepcopy(lst) 
 -  m = len(temp_lst) 
 -  while (m): 
 -  m -= 1 
 -  i = randint(0, m) 
 -  temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m] 
 -  return temp_lst 
 - foo = [1,2,3] 
 - shuffle(foo) # [2,3,1] , foo = [1,2,3] 
 
  
28. 展开列表 
此方法将类似javascript中[].concat(…arr)这样的列表展开。 
- def spread(arg): 
 -  ret = [] 
 -  for i in arg: 
 -  if isinstance(i, list): 
 -  ret.extend(i) 
 -  else: 
 -  ret.append(i) 
 -  return ret 
 - spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9] 
 
  
29. 交换变量 
此方法为能在不使用额外变量的情况下快速交换两种变量。 
- def swap(a, b): 
 -  return b, a 
 - a, b = -1, 14 
 - swap(a, b) # (14, -1) 
 
  
30. 获取丢失部分的默认值 
以下代码可在所需对象不在字库范围内的情况下获取默认值。 
- d = {'a': 1, 'b': 2} 
 - print(d.get('c', 3)) # 3 
 
  
本文只简单介绍了一些能在日常工作中帮到我们的方法。但内容都主要立足于GitHub  存储库:https://github.com/30-seconds/30_seconds_of_knowledge 
,该存储库还包含了有关Python及其他语言和技术行之有效的代码。                          (编辑:91站长网) 
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! 
                     |