5个小技巧,让你的for循环瞬间高大上!

开发 后端
如何让你的for循环告别繁复拥抱简洁,如何重启探索Python循环迭代的大门,希望以下几个小技巧能够给你启发。

本文转载自公众号“读芯术”(ID:AI_Discovery)

或许每个初学Python的程序员最早接触的概念中都有For循环,这一点理所当然, for循环可以在不费吹灰之力的情况下对数据执行很多操作。

然而,大量的使用for循环也可能会让使用者的思维拘泥于简单的迭代中,而忽略了一些更加高效且简洁的迭代方法。

如何让你的for循环告别繁复拥抱简洁,如何重启探索Python循环迭代的大门,希望以下几个小技巧能够给你启发。

Zip:同时在两个列表中循环

笔者在实践中发现代码可以同时在两个数组中进行循环。要想在其他的编程语言中做到这一点相对来说难度大很多,这也体现出了Python的简易性。要达到同时在两个数组中进行循环这一目的,只需使用zip()函数。

  1. for first,second in zip(array1,array2): 
  2.     print(first) 
  3.     print(second) 

在一个偶整数序列和一个奇整数序列中使用这一方法就能体现出这一函数的功效。

  1. odds = [1,3,5,7,9] 
  2. evens = [2,4,6,8,10] 
  3. for oddnum, evennum in zip(odds,evens): 
  4.     print(oddnum) 
  5.     print(evennum) 

以上函数输出的结果便是:

  1. 10 

In Range函数:编写C-Style循环

C-Style似乎看起来有点儿平凡,但它能在循环中焕发光彩。

  1. for i in range(10): 
  2.     print(i) 
  3.     if i == 3: 
  4.         i.update(7) 

C语言爱好者可能觉得以上的代码并不是C-Style循环,但如果不想自己动手编写迭代函数,以上内容已经是最完美的形式了。

不过笔者热衷于“浪费时间”,因此决定编写一个新的迭代程序来写出尽可能完美的C-Style循环。

  1. class forrange: 
  2.  
  3.     def __init__(self, startOrStop,stop=Nonestep=1): 
  4.         if step == 0: 
  5.             raise ValueError('forrangestep argument must not be zero') 
  6.         if not isinstance(startOrStop,int): 
  7.             raise TypeError('forrangestartOrStop argument must be an int') 
  8.         if stop is not None and notisinstance(stop, int): 
  9.             raise TypeError('forrangestop argument must be an int') 
  10.  
  11.         if stop is None: 
  12.             self.start = 0 
  13.             self.stop = startOrStop 
  14.             self.step = step 
  15.         else: 
  16.             self.start = startOrStop 
  17.             self.stop = stop 
  18.             self.step = step 
  19.  
  20.     def __iter__(self): 
  21.         returnself.foriterator(self.start, self.stop, self.step) 
  22.  
  23.     class foriterator: 
  24.  
  25.         def __init__(self, start, stop,step): 
  26.             self.currentValue = None 
  27.             self.nextValue = start 
  28.             self.stop = stop 
  29.             self.step = step 
  30.  
  31.         def __iter__(self): return self 
  32.  
  33.         def next(self): 
  34.             if self.step > 0 andself.nextValue >= self.stop: 
  35.                 raise StopIteration 
  36.             if self.step < 0 andself.nextValue <= self.stop: 
  37.                 raise StopIteration 
  38.             self.currentValue =forrange.forvalue(self.nextValue, self) 
  39.             self.nextValue += self.step 
  40.             return self.currentValue 
  41.  
  42.     class forvalue(int): 
  43.         def __new__(cls, value,iterator): 
  44.             value =super(forrange.forvalue, cls).__new__(cls, value) 
  45.             value.iterator = iterator 
  46.             return value 
  47.  
  48.         def update(self, value): 
  49.             if not isinstance(self, int): 
  50.                 raiseTypeError('forvalue.update value must be an int') 
  51.             if self ==self.iterator.currentValue: 
  52.                 self.iterator.nextValue =value + self.iterator.step 

Filter()函数:只对需要的数据进行循环

在处理大量的数据时,使用filter函数能够使得数据在使用时效果更佳。Filter函数正如其名,其功效是在对数据进行迭代前进行过滤。当只需要使用某一范围内的数据而且不想再添加一个条件时,filter十分实用。

  1. people = [{"name": "John","id": 1}, {"name": "Mike", "id": 4},{"name": "Sandra", "id": 2}, {"name":"Jennifer", "id": 3}]for person in filter(lambda i:i["id"] % 2 == 0, people): 
  2. ...     print(person) 
  3. ... 
  4. {'name': 'Mike', 'id': 4} 
  5. {'name': 'Sandra', 'id': 2} 

Enumerate()函数:对维度进行索引

在Python中使用枚举函数可以让Python将从数组中输出的列表索引进行编号。笔者制作了一个包含三个元素的列表对这一功能进行展示:

  1. l = [5,10,15] 

现在可以利用以下方法来访问数组索引:

  1. l[1] 
  2. 10 
  3. l[0] 
  4. l[2] 
  5. 15 

在这些列表中进行枚举时,维度的索引位置和维度会结合产生一个新的变量。请注意这一新变量的类型。

Python会自动将这些索引置入一个元组之中,这一点十分奇怪。笔者还是倾向于从只有一个元素的Python库中获得这些结果。还好,我们可以把这些枚举函数置入到一个Python库中。

  1. data = dict(enumerate(l)) 

输入以上代码之后就会得出:

  1. >>> data 
  2. {0: 5, 1: 10, 2: 15} 

[[324869]]

图源:unsplash

Sorted()函数:使用数据中进行排序,而非使用前

Sort函数对于常常需要处理大量数据的人来说至关重要,它将字符串根据首字母A到B进行排列,将整数和倍数自负无穷起由小至大排列。需要注意的是,这一函数无法用于带有字符串和整数或浮点数的列表。

  1. l = [15,6,1,8] 
  2. for i in sorted(l): 
  3.     print(i) 
  4. 15 

也可以将相反的参数设为False来进行逆运算。

  1. for i in sorted(l,reverse = True): 
  2.     print(i) 
  3. 15 

对于可用的最后一个参数,可以使用key函数。Key是一个应用于已知循环中的每个维度的函数。而笔者偏向于使用lambda,Lambda会创造一个匿名但仍可调用的函数。

  1. l.sort(key=lambda s: s[::-1]) 

写代码时,遇到大量的带有迭代的数据在所难免。简洁成就卓越,这些方法能够使代码简洁明了并且运行起来更快。循环的世界值得你继续探索!

 

责任编辑:赵宁宁 来源: 读芯术
相关推荐

2014-05-16 11:18:14

浏览器ChromeFirefox

2019-04-02 09:23:40

设计模式前端JavaScript

2024-01-08 17:09:07

Python解释器CPython

2009-10-27 09:09:06

Eclipse技巧

2020-04-20 15:07:50

性能优化低效循环程序

2022-01-06 22:31:21

Python技巧代码

2023-05-10 08:32:42

ISlidePPT插件工具

2019-12-03 08:59:13

Windows电脑软件

2017-04-13 11:45:56

报表大数据应用

2024-02-26 18:11:08

Docker容器镜像

2009-05-04 09:11:28

GoogleChrome浏览器

2020-02-26 21:57:09

Lambdajava8方法引用

2017-09-08 08:43:39

iOS 11SafariPDF

2020-07-08 17:06:00

Python开发工具

2023-02-22 17:51:10

VS code插件技巧

2018-06-20 11:00:06

云应用开发PaaS

2023-12-06 13:43:00

python代码

2019-04-29 08:31:25

PythonPandas数据

2018-09-03 14:49:27

Python实战项目

2020-11-29 17:32:01

EmacsLinux
点赞
收藏

51CTO技术栈公众号