Quickly grasp the loop technology in Python

HuangWeiAI 2021-01-21 11:52:30
quickly grasp loop technology python


Preface

Python The most basic recycling technology is for sentence , It can traverse any sequence ( List or string ) Projects in China , In the order they appear in the sequence . This article will give a comprehensive introduction to for The technique of circulation and its practical usage .

1. Use enumerate() Loop the entire sequence :

When a loop traverses a sequence ( As listing 、 Tuples 、 Scope object 、 character string ) when , have access to enumerate() Function to retrieve both the location index and the corresponding value .

Use enumerate() Traverse the list :

Example 1:

Use enumerate() Function traverses the list , Returns a tuple containing the count and value of an iteratable object . In general , Count from 0 Start .

colors=['red','green','blue']
for color in enumerate(colors):
print (color)
#Output:
(0, 'red')
(1, 'green')
(2, 'blue')

Example 2:

count from 5 Start looping iterators .

colors=['red','green','blue']
for color in enumerate(colors,5):
print (color)
'''
Output:
(5, 'red')
(6, 'green')
(7, 'blue')
'''

Use enumerate() Loop string :

Example :

Use enumerate() The function traverses the string and returns a tuple containing the count and value of the iteratable object . In general , Count from 0 Start .

s='python'
for i in enumerate(s):
print (i)
'''
#Output:
(0, 'p')
(1, 'y')
(2, 't')
(3, 'h')
(4, 'o')
(5, 'n')
'''

2. Use zip() Functions loop two or more sequences :

To cycle two or more sequences at the same time , have access to zip() Function to pair entries .

Use zip() Loop two sequences of the same length

Example :

num = [1, 2, 3]
colors= ['red', 'blue', 'green']
for i in zip(num, colors):
print(i)
'''
Output:
(1, 'red')
(2, 'blue')
(3, 'green')
''

Use zip() Loop two sequences of different lengths

If you use zip() Traversing two sequences of different lengths means stopping when the shortest iteratable object runs out .

Example :

colors=['red','green','blue']
num=[1,2,3,4,5,6,7,8,9,10]
for i in zip(colors,num):
print (i)
'''
Output:
('red', 1)
('green', 2)
('blue', 3)
'''

Use zip() Loop two or more sequences :

Example :

colors=['red','apple','three']
num=[1,2,3]
alp=['a','b','c']
for i in zip(colors,num,alp):
print (i)
'''
Output:
('red', 1, 'a')
('apple', 2, 'b')
('three', 3, 'c')
'''

3.itertools.zip_longest ()

Create an iterator that aggregates elements from each iteratable object . If the length of the iteratable object is not uniform , Then use fillvalue Fill in the missing values . Iteration continues , Until the longest iteratable object runs out .

Use itertools.zip_longest() Loop two sequences of different lengths .

Example 1:

If you don't specify fillvalue, The default is None.

from itertools import zip_longest
colors=['red','apple','three']
num=[1,2,3,4,5]
for i in zip_longest(colors,num):
print (i)
'''
Output:
('red', 1)
('apple', 2)
('three', 3)
(None, 4)
(None, 5)
'''

Example 2:

Appoint fillvalue.

from itertools import zip_longest
colors=['red','apple','three']
num=[1,2,3,4,5]
for i in zip_longest(colors,num,fillvalue='z'):
print (i)
'''
Output:
('red', 1)
('apple', 2)
('three', 3)
('z', 4)
('z', 5)
'''

4. Use sorted() The function loops through the sequence in the sorted order :

sorted():

from iterable Returns a new sorted list .

Example :1

Use sorted() Functions are sorted by ( Ascending ) Ergodic sequence (list).

num=[10,5,20,25,30,40,35]
for i in sorted(num):
print (i)
'''
Output:
5
10
20
25
30
35
40
'''

Example 2:

Use sorted() Functions are sorted by ( Descending ) Ergodic sequence (list).

num=[10,5,20,25,30,40,35]
for i in sorted(num,reverse=True):
print (i)
'''
Output:
40
35
30
25
20
10
5
'''

Example 3:

Use sorted() Functions are sorted by ( Ascending ) Ergodic dictionary . By default , It will sort the keys in the dictionary .

d={'f':1,'b':4,'a':3,'e':9,'c':2}
for i in sorted(d.items()):
print (i)
#Output:
('a', 3)
('b', 4)
('c', 2)
('e', 9)
('f', 1)

Example 4:

Loop the dictionary in sorted order using sorted functions . Use... In sorted functions key Parameters , Sort the dictionary by its value .

d={'f':1,'b':4,'a':3,'e':9,'c':2}
#sorting by values in the dictionary
for i in sorted(d.items(),key=lambda item:item[1]):
print (i)
#Output:
('f', 1)
('c', 2)
('a', 3)
('b', 4)
('e', 9)

5. Use reversed() Function traversal sequence :

reversed(seq)

Returns the reverse iterator .seq Must be a person with __reversed__() Method or support sequence protocol (__len__() Methods and __getitem__() Method , Parameter from 0 Start ) The object of .

Example :

Reverse loop a sequence , And then call reversed() function .

colors=['red','green','blue','yellow']
for i in reversed(colors):
print (i)
'''
Output:
yellow
blue
green
red
'''

6. Loop through the dictionary .

When you loop through the dictionary , have access to items() Method to retrieve both the key and the corresponding value .

Example :

d={'a':1,'b':2,'c':3}
for k,v in d.items():
print (k,v)
#Output:
a 1
b 2
c 3

7. Modify the set at iteration time :

When traversing the same collection, the code that modifies the collection can be difficult to handle properly . contrary , It's usually easier to loop through a copy of a collection or create a new one .

Strategy 1: Iterate over the replica

If you want to delete entries in the dictionary during iteration , Then iterate over a copy of the dictionary

d={'a':1,'b':2,'c':3}
for k,v in d.copy().items():
if v%2==0:
del d[k]
print (d)
#Output:{'a': 1, 'c': 3}

Strategy 2: Create a new collection

d={'a':1,'b':2,'c':3}
d1={}
for k,v in d.items():
if v%2!=0:
d1[k]=v
print (d1)
#Output:{'a': 1, 'c': 3}
print (d)
#Output:{'a': 1, 'b': 2, 'c': 3}

·END·

This article is from WeChat official account. - Python Learn to (gh_39aead19f756)

The source and reprint of the original text are detailed in the text , If there is any infringement , Please contact the yunjia_community@tencent.com Delete .

Original publication time : 2021-01-08

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[HuangWeiAI]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/01/20210121114922548a.html

  1. Python批量 png转ico
  2. 使用line_profiler对python代码性能进行评估优化
  3. 使用line_profiler对python代码性能进行评估优化
  4. Getting started with Python 3 flash in win environment
  5. Common ways to write configuration files in Python
  6. Python会在2021年死去吗? Python 3.9最终版本的回顾
  7. Python batch PNG to ICO
  8. Using line_ Profiler evaluates and optimizes the performance of Python code
  9. Using line_ Profiler evaluates and optimizes the performance of Python code
  10. Will Python die in 2021? A review of the final version of Python 3.9
  11. Python3 SMTP send mail
  12. Understanding closures in Python: getting started with closures
  13. Python日志实践
  14. Python logging practice
  15. [python opencv 计算机视觉零基础到实战] 十、图片效果毛玻璃
  16. [python opencv 计算机视觉零基础到实战] 九、模糊
  17. 10. Picture effect ground glass
  18. [Python opencv computer vision zero basis to actual combat] 9. Fuzzy
  19. 使用line_profiler對python程式碼效能進行評估優化
  20. Using line_ Profiler to evaluate and optimize the performance of Python code
  21. LeetCode | 0508. 出现次数最多的子树元素和【Python】
  22. Leetcode | 0508
  23. LeetCode | 0530. 二叉搜索树的最小绝对差【Python】
  24. LeetCode | 0515. 在每个树行中找最大值【Python】
  25. Leetcode | 0530. Minimum absolute difference of binary search tree [Python]
  26. Leetcode | 0515. Find the maximum value in each tree row [Python]
  27. 我来记笔记啦-搭建python虚拟环境
  28. Let me take notes - building a python virtual environment
  29. LeetCode | 0513. 找树左下角的值【Python】
  30. Leetcode | 0513. Find the value in the lower left corner of the tree [Python]
  31. Python OpenCV 泛洪填充,取经之旅第 21 天
  32. Python opencv flood fill, day 21
  33. Python爬虫自学系列(二)
  34. Python crawler self study series (2)
  35. 【python】身份证号码有效性检验
  36. [Python] validity test of ID number
  37. Python ORM - pymysql&sqlalchemy
  38. Python ORM - pymysql&sqlalchemy
  39. centos7 安装python3.8
  40. centos7 安装python3.8
  41. Centos7 installing Python 3.8
  42. Centos7 installing Python 3.8
  43. Django——图书管理系统(六)
  44. Django——图书管理系统(五)
  45. Django -- library management system (6)
  46. Django -- library management system (5)
  47. python批量插入数据小脚本
  48. Python batch insert data script
  49. ZoomEye-python 使用指南
  50. Zoomeye Python User's Guide
  51. 用Python写代码,一分钟搞定一天工作量,同事直呼:好家伙 - 知乎
  52. Using Python to write code, one minute to complete a day's workload, colleagues call: good guy - Zhihu
  53. Python 上的可视化库——PyG2Plot
  54. Pyg2plot: a visualization library on Python
  55. Python 上的可视化库——PyG2Plot
  56. Python实用代码-无限级分类树状结构生成算法
  57. Pyg2plot: a visualization library on Python
  58. Python utility code - infinite classification tree structure generation algorithm
  59. 奇技淫巧,还是正统功夫?Python推导式最全用法
  60. Pandas 的这个知识点,估计 80% 的人都得挂!