Coding mistakes that Python programmers often make (2)

1 Introduction

This article is the second part of the coding mistakes that Python programmers often make. In the previous article, we focused on five common mistakes. This article continues to introduce this topic. I hope you can pay more attention to it in your daily life.
Without further ado, let's get started!

2. Use for loop to find an element in the list

(1). General plan

Suppose we need to find whether an element exists in a list (or set) and return a Boolean value (i.e. True if present, False otherwise). As follows:
insert image description here
Well, such a simple function, too many lines of code.
(2). Elegant solution

Recommended keywords inWe can simplify this to a one-liner implementation as follows:
insert image description here

3. Iterate over two lists of the same size using an index

(1). General solution
In order to realize the above functions, we can first define an index variable to iterate at the same time, as shown below:
insert image description here
(2). Elegant solution

A more concise way is to use functions zip(), examples are as follows:
insert image description here

4. Reverse a list using a for loop

Image examples are as follows:
insert image description here
(1). General scheme

In general, we can use a for loop to iterate the list in reverse, and add the corresponding elements to the new list, as follows:
insert image description here
(2). Elegant solution

If we understand the slicing operation of lists in Python, the elegant solution is just a simple one-liner:
insert image description here

5. Use for loop to judge palindrome

(1). General plan

Following the idea of ​​the above case (reversed list), we can check if the reversed list is the same as the input list. As follows:
insert image description here
(2). Elegant solution
As mentioned above, a more elegant method is to use a slice and compare it with the input list, as follows:
insert image description here

6. Use for to count the frequency of an element in the list

(1). General plan

The easiest way to find the frequency of an element in a list is to use a for loop to iterate through the list and count the number of occurrences. As follows:
insert image description here

(2). Elegant solution

In this case, the relatively elegant way to avoid us writing for loops is to use functions count(), like this:
insert image description here

7. Summary

This article summarizes the mistakes that Python programmers often make, and gives corresponding concise solutions for your reference.

Are you useless?

Guess you like

Origin blog.csdn.net/sgzqc/article/details/127454779