当前位置: 首页 > 问答 > Python编程 > 问答详情

python中如何实现遍历整个列表?

01月07日 05:061040人阅读
许老师 Python编程

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!

职业技能申请领取
您的姓名
您的电话
意向课程
点击领取

环球青藤

官方QQ

扫描上方二维码或点击一键加群,免费领取大礼包,加群暗号:青藤。 一键加群

问答来自

许老师 Python编程
好评率85% 浏览1040

相关问题

python字典遍历的方法有哪些?
张老师 Python编程
python中如何进行集合交集运算?
刘老师 Python编程
python中如何删除list元素?
张老师 Python编程
课程咨询 学员服务 公众号

扫描关注微信公众号

APP

扫描下载APP

返回顶部