Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to quickly master the cycle technology in Python

2025-04-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to quickly master the loop technology in Python". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to quickly master the loop technology in Python".

1. Use enumerate () to loop the entire sequence

When iterating through a sequence (such as lists, tuples, range objects, strings), you can use the enumerate () function to retrieve both the location index and the corresponding values.

(1) use enumerate () to traverse the list:

Example 1:

Use the enumerate () function to iterate through the list and return a tuple containing the count and value in the iterable object. In general, the count starts at 0.

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

Example 2:

Count loops the iterator from 5.

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

(2) use enumerate () to loop the string:

Example:

Traversing the string using the enumerate () function returns a tuple containing the count and value of the iterable object. In general, the count starts at 0.

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

two。 Use the zip () function to cycle through two or more sequences

To cycle through two or more sequences at the same time, you can use the zip () function to pair items.

(1) use zip () to cycle through 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')'

(2) use zip () to cycle through two sequences of different length.

If you use zip () to iterate through two sequences of different lengths, it means stopping when the shortest iterable object is exhausted.

Example:

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

(3) cycle through two or more sequences using zip ():

Example:

Colors= ['red','apple','three'] num= [1 apple', 2 dagger 3] alp= [' Aaqiang pageanagogue] 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 iterable object. If the length of the iterable object is uneven, the missing value is populated with fillvalue. Iterations continue until the longest iterable object is exhausted.

Use itertools.zip_longest () to cycle through two sequences of different lengths.

Example 1: if fillvalue is not specified, the default is None.

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

Example 2: specify fillvalue.

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

4. Use the sorted () function to cycle through the sequence in the sorted order

Sorted (): returns a new sorted list from the items in iterable.

Example: 1 use the sorted () function to sort (ascend) through the sequence (list).

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

Example 2: use the sorted () function to sort (descend) through a sequence (list).

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

Example 3: use the sorted () function to traverse the dictionary in ascending order. By default, it sorts the keys in the dictionary.

D = for i in sorted (d.items ()): print (I) # Output: ('baked, 3) (' baked, 4) ('eyed, 9) (' favored, 1)

Example 4: use sorted functions to loop dictionaries in sorted order. Use the key parameter in the sorted function to sort it according to the value of the dictionary.

D = # sorting by values in the dictionary for i in sorted (d.items (), key=lambda item:item [1]): print (I) # Output: ('foggy, 1) (' cantilevered, 2) ('baked, 3) (' baked, 4) ('eyed, 9)

5. Use the reversed () function to traverse the sequence

Reversed (seq):

Returns the reverse iterator. Seq must be an object that has a _ _ reversed__ () method or supports sequence protocols (_ _ len__ () method and _ _ getitem__ () method, with arguments starting from 0).

Example:

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

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

6. Circular lookup dictionary

When you loop through the dictionary, you can use the items () method to retrieve both the key and the corresponding value.

Example:

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

7. Modify the collection during iteration

The code that modifies the collection when traversing the same collection can be difficult to handle correctly. In contrast, it is usually easier to loop through a copy of a collection or to create a new collection.

Strategy 1: iterate over the copy

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

D = {'axianglu 1ZHANGZHUANG 2ZHANGZHANGZHANG 3} for kMene v in d.copy (). Items (): if v% 2ZOBG 0: del d [k] print (d) # Output: {'aqiughuzhul' cantilever3}

Strategy 2: create a new collection

D = {'afiughuanlu 1D1= {} for kMagne v in d.items (): if v% 1ZOBZO0: D1 [k] = v print (D1) # Output: {' axiaqizhuo 1magnum 'cantilevered Output 3} print (d) # Output: {' axianglangzhuanghuanghuanghuanghuanzhanghuanghuanghuanghuanzhongzhuangzhuo () thank you for your reading. The above is the content of "how to quickly master the loop technology in Python". After the study of this article, I believe you have a deeper understanding of how to quickly master the loop technology in Python, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report