Python 入门系列 —— 15. List 四种遍历方式及推导式介绍

使用 for 遍历 List

能够使用 for 来遍历 List,代码以下:python

thislist = ["apple", "banana", "cherry"]
for x in thislist:
  print(x)

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
apple
banana
cherry

使用 index 遍历 List

除了直接使用 for 遍历,还能够组合 range() + len() 使用下标进行遍历,以下代码所示:git

thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
  print(thislist[i])

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
apple
banana
cherry

使用 while 遍历 List

使用 len() 来判断 list 的长度,而后从索引0 开始遍历 list 中的每一项,不过要记得在遍历时自增 index,以下代码所示:github

thislist = ["apple", "banana", "cherry"]
i = 0
while i < len(thislist):
  print(thislist[i])
  i = i + 1

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
apple
banana
cherry

使用 推导式 遍历 List

使用 python 独有的 推导式 直接快捷遍历 List。express

thislist = ["apple", "banana", "cherry"]
[print(x) for x in thislist]

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
apple
banana
cherry

List 推导式

当你想要从一个现有的 List 中生成一个新的 List,能够使用 推导式 这种快捷语法。markdown

举个例子:app

好比你有一个 fruits 列表,你想获取全部以 a 开头的水果名,若是没有推导式的话,只能像下面这样写。oop

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []

for x in fruits:
  if "a" in x:
    newlist.append(x)

print(newlist)

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
['apple', 'banana', 'mango']

要是用 推导式 的话,只要一行代码就能够搞定,以下代码所示:ui

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]

print(newlist)


PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
['apple', 'banana', 'mango']

语法分析

语法格式以下: newlist = [expression for item in iterable if condition == True] 。能够看出,返回值是一个新的 list,同时也不会破坏原有的list。this

condition

语法格式中的 condition,用于保留枚举项判断为 true 的元素,非 true 就忽略了,code

iterable

iterable 表示可迭代的集合,如: list,tuple,set 等等。

expression

这里的 expression 就是当前的迭代变量值,在这个迭代项准备送入到新集合前,能够对它进行操控,好比下面的例子:

newlist = [x.upper() for x in fruits]
译文连接: https://www.w3schools.com/pyt...

更多高质量干货:参见个人 GitHub: python

相关文章
相关标签/搜索