python学习03——列表


列表相当于Java中的数组, python中的列表可以 存储任意类型的元素,同时列表会根据存储内容 动态分配内存

1 创建列表

1.1 使用[]创建列表

mylist = ["hello", "word", 98]
print(mylist)  # ['hello', 'word', 98]

1.2 使用内置函数list()创建列表

mylist2 = list(["hello", "word", 2022])
print(mylist2)  # ['hello', 'word', 2022]

2 查询元素

2.1 index()函数

2.1.1 如果列表有多个重复元素,index()只返回第一个元素的索引。
mylist = ["hello", "word", 98, "hello"]

print(mylist.index("hello"))  # 0
2.1.2 如果列表中没有此元素,则会抛出异常。
mylist = ["hello", "word", 98, "hello"]

print(mylist.index("python"))  

抛出异常:

Traceback (most recent call last):
  File "D:\pythonStudy\fistproject\demo11.py", line 3, in <module>
    print(mylist.index("python"))  
ValueError: 'python' is not in list
2.1.3 可以指定查询位置。

使用index(obj, start, end)查询元素位置,从startend前一位,**不包括end**位置。

mylist = ["hello", "word", 98, "hello"]

print(mylist.index("hello", 1, 4))  # 3

可以看见,查询的范围是:"word", 98, "hello"

2.2 获取指定索引位置的元素

Java类型,但是要注意一点,python中索引可以是负数:

  • 正向索引:元素从0N-1
  • 逆向索引:元素从-N-1
mylist = ["hello", "word", 98, "python"]

# 正向索引
print(mylist[3])  # python
# 逆向索引
print(mylist[-1])  # python

2.3 列表的切片

列表的切片就是列表的拷贝语法为列表名[start: stop: step],其中,不包含stop的元素

  • 切片后的列表,是新的列表,和原列表的ID不一样
  • 切片的范围:[start, stop)
  • 步长step默认为1
  • step为正数时,从start开始往后切片:
    • [: stop: step]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值