Python入门 — 操作列表

目录

一、遍历列表

二、创建数值列表

1、range() 函数

2、range() 创建数值列表

3、列表推导式

三、使用列表的部分元素

1、切片

2、复制列表

四、元组


一、遍历列表

和所有编程语言一样,首先可以考虑 for 循环

egs = [ 'aa', 'bb', 'cc' ]
for eg in egs:
    print(eg)

定义了一个列表,并定义一个 for 循环,:对于(for)列表 egs 中的每位 eg,都打印(print)元素 eg。输出结果如下:

aa

bb

cc

然后再写一个稍微复杂点的 for 循环

magicians = ['alice', 'david', 'carolina']
for magician in magicians:
    print(f"{magician.title()}, that was a great trick!")
    print(f"I can't wait to see your next trick, {magician.title()}.\n")
print("Thank you, everyone. That was a great magic show!")

注意:Python 根据缩进来判断代码行与程序其他部分的关系

输出结果如下:

Alice, that was a great trick!
I can't wait to see your next trick, Alice.


David, that was a great trick!
I can't wait to see your next trick, David.


Carolina, that was a great trick!
I can't wait to see your next trick, Carolina.


Thank you, everyone. That was a great magic show!

在 for 循环后面,没有缩进的代码都只执行一次。

二、创建数值列表

列表非常适合用于存储数值集合,而 Python 提供了很多工具&#

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值