Python Series Tutorial 162 - More Complex List Comprehension

Friends, if you need to reprint, please indicate the source: blog.csdn.net/jiangjunsho…

Disclaimer: During the teaching of artificial intelligence technology, many students asked me some python-related questions, so in order to let the students have more extended knowledge and a better understanding of AI technology, I asked my assistant to be responsible for sharing this series of python tutorials. I hope Can help everyone! Since this python tutorial is not written by me, it is not as funny and humorous as my AI technology teaching, and it is more boring to learn; but its knowledge points are still in place, and it is worth reading! Students who want to learn AI technology can click to jump to my teaching website . PS: For students who do not understand this article, please read the previous article first, and you will not find it difficult to learn a little bit every day step by step!

List comprehensions can have more advanced applications. For example, a for loop nested within an expression can have an associated if clause that filters out items that test false. Suppose we want to do a file scan, however, we only need to collect those lines that start with the letter p:

>>>lines = [line.rstrip() for line in open('script1.py') if line[0] == 'p']

>>>lines

['print(sys.path)','print(2 ** 33)']
复制代码

This if clause checks each line read from the file to see if its first character is a p; if not, the line is omitted from the resulting list. Of course we can convert it to the equivalent of a for loop statement:

>>>res = []

>>>for line in open('script1.py'):

...    if line[0] == 'p':

...        res.append(line.rstrip())

...

>>>res

['print(sys.path)','print(2 ** 33)']
复制代码

This for statement equivalent also works, however, it takes up 4 lines instead of one, and may run a lot slower.

List comprehensions can get more complex if we need to - for example, they might contain nested loops, or they might be written as a series of for clauses. For example, the following example builds an x+y concatenated list, concatenating each x in one string with each y in the other:

>>>[x + y for x in 'abc' for y in 'lmn']

['al','am','an','bl','bm','bn','cl','cm','cn']
复制代码

The following is the equivalent of its for loop:

>>>res = []

>>>for x in 'abc':

...    for y in 'lmn':

...        res.append(x + y)

...

>>>res

['al','am','an','bl','bm','bn','cl','cm','cn']
复制代码

Guess you like

Origin juejin.im/post/7078495113499901983