博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python中如何遍历列表并将列表值赋予_python中如何实现遍历整个列表?
阅读量:1534 次
发布时间:2019-04-21

本文共 1120 字,大约阅读时间需要 3 分钟。

在python列表中,遍历是我们必学的操作。它可以帮助我们访问到每一个元素。python中可以使用 for 循环来打印列表中的所有元素,即实现遍历整个列表。本文将详细介绍用for循环遍历的过程和通过一个练习帮助大家理解。

1、for循环

使用 for 循环来打印列表中的所有元素。#代码:

names = ['张三','李四','王五']

for name in names:

print(name)

#执行结果:

张三

李四

王五

2、for 循环中执行更多操作

使用 for 循环来打印列表中的所有元素,并祝福每位客人新年快乐。#代码:

names = ['张三','李四','王五']

for name in names:

print("{}{}".format(name,',新年快乐\n'))

#执行结果:

张三,新年快乐

李四,新年快乐

王五,新年快乐

3、for 循环结束后执行一些操作

在 for 循环结束后祝大家新年快乐#代码:

names = ['张三','李四','王五']

for name in names:

print("{}{}".format(name,',新年快乐\n'))

print('I wish you all happy new year')

#执行结果:

张三,新年快乐

李四,新年快乐

王五,新年快乐

I wish you all happy new year

4 、练习

相出三种有共同特征的动物,将其名称存储在一个列表中,再使用 for 循环将每动物的名称打印出来。

修改这个程序,使其针对每种动物都打印一个句子。

再程序的末尾添加一行代码,指出这些动物的共同之处。#代码:

animals = ['dog','cat','pig']

for animal in animals:

print(f"A {animal} would make a great pet.")

#format 打印

#    print("{}{}{}".format('A ',animal,'would make a great pet.'))

print('Any of these animals would make a great pet!')

#执行结果:

A dog would make a great pet.

A cat would make a great pet.

A pig would make a great pet.

Any of these animals would make a great pet!

以上就是python中用for循环实现列表遍历的方法,大家可以尝试看看哦~

转载地址:http://waydy.baihongyu.com/

你可能感兴趣的文章
【英语学习】【Level 08】U01 Let's Read L3 The classics are always in
查看>>
【英语学习】【Level 08】U01 Let's Read L4 Hot off the press
查看>>
【英语学习】【Level 08】U01 Let's Read L5 You're a wizard, Harry.
查看>>
【英语学习】【Level 08】U01 Let's Read L6 Person of the year
查看>>
【英语学习】【Level 08】U02 Movie Time L1 Let's talk about movies
查看>>
【英语学习】【Level 08】U02 Movie Time L2 In black and white
查看>>
【英语学习】【Level 08】U02 Movie Time L3 Now showing
查看>>
【英语学习】【Level 08】U02 Movie Time L4 From the page to the big screen
查看>>
【英语学习】【Level 08】U02 Movie Time L5 Art in motion
查看>>
【英语学习】【Level 08】U02 Movie Time L6 Blockbuster
查看>>
【英语学习】【Level 08】U03 My Choice L1 Good books are like good friends
查看>>
【英语学习】【Level 08】U03 My Choice L2 All-time favorite character
查看>>
【英语学习】【Level 08】U04 What I love L2 My favorite sport
查看>>
【Level 08】U07 Mixed Feelings L2 Let's go shopping
查看>>
【Level 08】U07 Mixed Feelings L3 I just want to have fun
查看>>
【Level 08】U07 Mixed Feelings L4 Learning by heart
查看>>
【Level 08】U07 Mixed Feelings L5 Front page news
查看>>
【英语学习】【化学】几个与氮(Nitrogen)有关的化学词汇 (1)
查看>>
Intel 64/x86_64/IA-32/x86处理器通用寄存器 (2) - 64位通用寄存器
查看>>
【英语学习】 - 君若不离不弃,吾当生死相依
查看>>