A detailed example of a for loop in Python

Source: Internet
Author: User
Tags python list
This article mainly describes Python in the use of the For loop in the process of shredding, the need for friends can refer to the following

Why challenge yourself not to write a for loop in your code? Because it can force you to use more advanced, authentic syntax or libraries. In this article, we take Python as an example, and say a lot of people have actually seen in other people's code, but they seldom use the grammar.

This is a challenge. I want you to avoid writing for loops under any circumstances. Likewise, I want you to find a scene that is too difficult to write in any other way except with a for loop. Please share your findings and I'd love to hear about them.

It's been a while since I started exploring awesome Python language features. At first, it was just a challenge for me to practice using more language features instead of what I learned from other programming languages. But things are getting more interesting! The code is not just getting shorter and neater, it looks more structured and regular, and I'll cover these benefits in more detail in this article.

First, let's take a step back and see what the intuition behind writing a For loop is:

1. Iterate through a sequence to extract some information

2. Generate an additional sequence from the current sequence

3. Write for loop is already my second nature, because I am a programmer

Fortunately, Python has great tools to help you achieve these goals! All you need to do is change your mind and look at the problem in different ways.

Don't go around writing for loops what you're going to get

1. Fewer lines of code

2. Better code Reading

3. Only indents are used to manage code text

Let's see the code skeleton below:

Look at the architecture of the following code:


# 1with ...: for  ...:    if ...:      try:      except:    else:

This example uses multiple layers of nested code, which is very difficult to read. I found it in this code. Use indentation to mix management logic (with, try-except) and business logic (for, if) together. If you follow a specification that uses indentation only for management logic, then the core business logic should be immediately detached.

"Flat structure is better than nested structure" – Zen of Python

To avoid a for loop, you can use these tools

1. List parsing/builder expressions

To see a simple example, this example compiles a new sequence based on an already existing sequence:


result = []for item in item_list:  new_item = Do_something_with (item)  Result.append (item)

If you like MapReduce, you can use the map, or the Python list to parse:

result = [do_something_with(item) for item in item_list]

Similarly, if you just want to get an iterator, you can use a builder expression that is almost interlinked with the syntax. (How can you not fall in love with python consistency?) )

result = (do_something_with(item) for item in item_list)

2. Functions

Standing in a higher order, more functional into a way to think about it, if you want to map a sequence to another sequence, call the map function directly. (You can also use list resolution instead.) )

doubled_list = map(lambda x: x * 2, old_list)

If you want to reduce a sequence to an element, use reduce


From functools Import reducesummation = reduce (lambda x, y:x + y, numbers)

In addition, a large number of embedded features in Python can be (I don't know if it's a good thing or a bad thing, you pick one, don't add this sentence a bit difficult to understand) consume iterators:


>>> A = List (range) >>> a[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> all (a) false>>> any (a) Tru E>>> Max (a) 9>>> min (a) 0>>> list (filter (bool, a)) [1, 2, 3, 4, 5, 6, 7, 8, 9]>>> set (a) { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}>>> dict (Zip (a,a)) {0:0, 1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8, 9:9}>&G T;> Sorted (A, reverse=true) [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]>>> str (a) ' [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ' >>> ; Sum (a) 45

3. Extracting a function or an expression

The two methods above handle the simpler logic well, what about the more complex logic? As a programmer, we will abstract difficult things into functions, which can also be used here. If you write down this code:


results = []for item in Item_list:  # setups  # condition  # processing  # calculation  results.append ( Result

Obviously you've given too much responsibility for a piece of code. To improve, I suggest you do this:


def process_item (item):  # setups  # condition  # processing  # calculation  return resultresults = [ Process_item (item) for item in Item_list]

What about nested for loops?


results = []for i in range]: for  J in Range (i):    results.append ((i, J))

List parsing can help you:


results = [(i, J) for      I in range (Ten) for      J in Range (i)]

What if you want to save a lot of internal state?


# Finding the Max prior to the current Itema = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]results = []current_max = 0for i in a:  cu Rrent_max = Max (i, Current_max)  results.append (current_max) # results = [3, 4, 6, 6, 6, 9, 9, 9, 9, 9]

Let's extract an expression to implement these:


def max_generator (numbers):  Current_max = 0 for  i in numbers:    Current_max = max (i, Current_max)    yield Current_maxa = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]results = List (Max_generator (a))

"Wait, you just used a for loop in that function expression, that's cheating!" ”

All right, smart guy, try this one.

4. Don't write your for loop yourself, Itertools will do it for you.

This module is really wonderful. I believe this module can cover 80% of the time you want to write a for loop. For example, the previous example could be rewritten like this:


From itertools Import Accumulatea = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]RESUTLS = List (accumulate (a, max))

In addition, if you are in the sequence of iterations, there is product (), permutations (), combinations () can be used.

Conclusion

1. In most cases it is not necessary to write a for loop.

2. You should avoid using a for loop, which makes your code more readable.

Let's go

1. Look again at your code and find out any place where you previously wrote the For loop with intuition, and think again whether it makes sense to write it again without a for loop.

2. Share an example of how hard it is to not use a for loop.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.