Python high-frequency interview questions - how to implement list deduplication

 

When interviewing for Python automation testing positions, one of the most frequently asked coding practical questions is:

A list contains multiple values, but there are duplicate values, how to achieve deduplication? Of course, you can also ask questions based on the actual business situation, such as: count how many different users use the system today, etc., so that you can better see whether the students being interviewed are memorizing the topic

Use set to deduplicate

The set() function creates an unordered and non-repeating element set, which can be used to test relationships, delete duplicate data, and calculate intersection, difference, and union. For this interview question, the easiest way is to convert our list into a set, automatically delete duplicate values, and finally convert the set into a list. The code implementation is as follows:

list1 = [1,1,2,3,4,6,6,2,2,9]
list2 = list(set(list1))
print(list2)
>>>[1, 2, 3, 4, 6, 9]

Loop implementation

Using the for loop, we will traverse the list to delete duplicate values. This is the basic operation of this interview question. The implementation idea is as follows:

First we create an empty list list3 = []. In the for loop, add to check whether the element in the list exists in list3, if not, use the append method to add the element to list3, whenever a duplicate value is encountered, since it is already in list3, it will not be deleted insert.

The code is implemented as follows:

list1 = [1,1,2,3,4,6,6,2,2,9]
list3 = []
for i in list1:
    if i not in list3:
        list3.append(i)
print(list3)
输出:
[1, 2, 3, 4, 6, 9]

final summary

A small test site, including the following important knowledge points of python:

1. The use of list

2. The use of set

3. The use of loop statements

4. The use of conditional statements

To be honest, if it’s not for rolls, for the recruitment of interface automation testing and UI automation testing positions, mastering the above-mentioned basic python knowledge point assessment can achieve the goal, and the students who pass are fully capable of writing related test scripts!

Every article of mine hopes to help readers solve problems encountered in actual work! If the article helped you, please like, bookmark, forward! Your encouragement is my biggest motivation to keep updating articles!

Guess you like

Origin blog.csdn.net/liwenxiang629/article/details/131701042