Python---list comprehension

Column: python
Personal homepage: HaiFan.
Column introduction: This column mainly updates some basic knowledge of python, and also implements some small games, address book, class time management system and so on. Interested friends can pay attention to it.

list comprehension


foreword

What are list comprehensions?

[表达式 for 变量 in 可迭代对象 [if 可迭代的if条件]]

A list comprehension is Pythona way of building a list, which makes it easier to implement some code to create a list.


For example, append some numbers to the end of the list one by one. If you have not been exposed to list comprehension, you will write for循环and then use the appendmethod to append at the end.

alist = list()

for i in range(1,101):
    alist.append(i)
print(alist)

Is this code too long? ? ?

Simplifications can be made with list comprehensions.

alist = list()

for i in range(1,101):
    alist.append(i)
print(alist)


blist = list()
blist = [i for i in range(1,101)]
print(blist)

insert image description here
Using list comprehensions, one line of code can do it.


Of course, it's not used here 可迭代的if条件.

So when you are asked to write an even number from 1 to 100 in the list, how would you write it? ?

blist = list()
blist = [i for i in range(0,101,2)]
print(blist)

clist = list()
clist = [i for i in range(0,101) if i % 2 == 0]
print(clist)

insert image description here
Even numbers can be added according to rangethe step size of , or it can be done with a list comprehension 可迭代if条件.

Guess you like

Origin blog.csdn.net/weixin_73888239/article/details/128778629