Simple understanding of Python list comprehension

Simply put, list comprehension provides a more convenient way to create a list, that is, replace the original few lines of code with one line. Its structure is as follows:

newlist = [expression for member in iterable (if conditional)]

The translation is, for an iterable object iterable, we take out a member from it each time, if it satisfies the condition conditional (if there is no condition, it is equivalent to directly being True), then put it into the expression function for processing, and add it to the newlist middle.

Note that if the outer square brackets are removed, the comprehension essentially returns a generator object, not a list:

print(type(i for i in range(1, 100)))
# <class 'generator'>

print(type([i for i in range(1, 100)]))
# <class 'list'>

Example 1

Suppose you want to create an integer array from 1 to 99, the original writing method is as follows:

ret = []
for i in range(1, 100):
	ret.append(i)
print(ret)

List comprehensions are written as follows:

ret = [i for i in range(1, 100)]
print(ret)

Example 2

Suppose you want to create an array of odd numbers from 1 to 99, the original writing method is as follows:

ret = []
for i in range(1, 100):
	if i % 2 == 1:
		ret.append(i)
print(ret)

List comprehensions are written as follows:

ret = [i for i in range(1, 100) if i % 2 == 1]
print(ret)

Example 3

Suppose you want to create an array containing square numbers from 1 to 9, the original way of writing is as follows:

ret = []
for i in range(1, 10):
	ret.append(i ** 2)
print(ret)

List comprehensions are written as follows:

ret = [i ** 2 for i in range(1, 10)]
print(ret)

Example 4

Assuming that element K is to be removed from the array, an original way of writing is as follows:

lst = [1, 2, 3, 4, 5, 3, 6]
K = 3

ret = []
for x in lst:
    if x != K:
        ret.append(x)
print(ret)

List comprehensions are written as follows:

lst = [1, 2, 3, 4, 5, 3, 6]
K = 3

ret = [x for x in lst if x != K]
print(ret)

It can be seen from here that the list comprehension is equivalent to the replacement of the filter function (and may even be more concise). The way to use filter is as follows:

lst = [1, 2, 3, 4, 5, 3, 6]
K = 3

ret = list(filter(lambda x: x != K, lst))
print(ret)

Guess you like

Origin blog.csdn.net/qq_40714949/article/details/131371414