十个极简Python代码,拿走即用,


虽然python是一个易入门的语言,但是很多人依然还是会问到底怎么样学 Python 才最快,答案当然是实战各种小项目,只有自己去想与写,才记得住规则。本文写的是 10 个极简任务,初学者可以尝试着自己实现;本文同样也是 10段代码,Python 开发者也可以看看是不是有没想到的用法。

1、重复元素判定

以下方法可以检查给定列表是不是存在重复元素,它会使用 set() 函数来移除所有重复元素。

  1. def all_unique(lst): 
  2. return len(lst)== len(set(lst)) 
  3. x = [1,1,2,2,3,2,3,4,5,6] 
  4. y = [1,2,3,4,5] 
  5. all_unique(x) # False 
  6. all_unique(y) # True 

2、分块

给定具体的大小,定义一个函数以按照这个大小切割列表。

  1. from math import ceil 
  2. def chunk(lst, size): 
  3. return list( 
  4. map(lambda x: lst[x * size:x * size + size], 
  5. list(range(0, ceil(len(lst) / size))))) 
  6. chunk([1,2,3,4,5],2) 
  7. # [[1,2],[3,4],5] 

3、压缩

这个方法可以将布尔型的值去掉,例如(False,None,0,“”),它使用 filter() 函数。

  1. def compact(lst): 
  2. return list(filter(bool, lst)) 
  3. compact([0, 1, False, 2, '', 3, 'a', 's', 34]) 
  4. # [ 1, 2, 3, 'a', 's', 34 ] 

4、 使用枚举

我们常用 For 循环来遍历某个列表,同样我们也能枚举列表的索引与值。

  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) 

5、解包

如下代码段可以将打包好的成对列表解开成两组不同的元组。

  1. array = [['a', 'b'], ['c', 'd'], ['e', 'f']] 
  2. transposed = zip(*array) 
  3. print(transposed) 
  4. # [('a', 'c', 'e'), ('b', 'd', 'f')] 

6、展开列表

该方法将通过递归的方式将列表的嵌套展开为单个列表。

  1. def spread(arg): 
  2. ret = [] 
  3. for i in arg: 
  4. if isinstance(i, list): 
  5. ret.extend(i) 
  6. else: 
  7. ret.append(i) 
  8. return ret 
  9. def deep_flatten(lst): 
  10. result = [] 
  11. result.extend( 
  12. spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst)))) 
  13. return result 
  14. deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5] 

7、 列表的差

该方法将返回第一个列表的元素,且不在第二个列表内。如果同时要反馈第二个列表独有的元素,还需要加一句 set_b.difference(set_a)。

  1. def difference(a, b): 
  2. set_a = set(a) 
  3. set_b = set(b) 
  4. comparison = set_a.difference(set_b) 
  5. return list(comparison) 
  6. difference([1,2,3], [1,2,4]) # [3] 

8、 执行时间

如下代码块可以用来计算执行特定代码所花费的时间。

  1. import time 
  2. start_time = time.time() 
  3. a = 1 
  4. b = 2 
  5. c = a + b 
  6. print(c) #3 
  7. end_time = time.time() 
  8. total_time = end_time - start_time 
  9. print("Time: ", total_time) 
  10. # ('Time: ', 1.1205673217773438e-05)  

9、 Shuffle

该算法会打乱列表元素的顺序,它主要会通过 Fisher-Yates 算法对新列表进行排序:

  1. from copy import deepcopy 
  2. from random import randint 
  3. def shuffle(lst): 
  4. temp_lst = deepcopy(lst) 
  5. m = len(temp_lst) 
  6. while (m): 
  7. m -= 1 
  8. i = randint(0, m) 
  9. temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m] 
  10. return temp_lst 
  11. foo = [1,2,3] 
  12. shuffle(foo) # [2,3,1] , foo = [1,2,3] 

10、 交换值

不需要额外的操作就能交换两个变量的值。

  1. def swap(a, b): 
  2. return b, a 
  3. a, b = -1, 14 
  4. swap(a, b) # (14, -1) 
  5. spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9] 

以上,是我简单列举的十个python极简代码,拿走即用,希望对你有所帮助!

评论关闭