python中使用序列(列表)的代码范例
列表、元组和字符串都是序列,但是序列是什么,它们为什么如此特别呢?序列的两个主要特点是索引操作符和切片操作符。索引操作符让我们可以从序列中抓取一个特定项目。切片操作符让我们能够获取序列的一个切片,即一部分序列。
""" 作者:皮蛋编程(https://www.pidancode.com) 创建日期:2022/3/21 功能描述:python中使用序列(列表)的代码范例 """ shoplist = ['pidancode.com', 'baidu.com', 'google.com', 'bandao.cn'] # Indexing or 'Subscription' operation print('Item 0 is', shoplist[0]) print('Item 1 is', shoplist[1]) print('Item 2 is', shoplist[2]) print('Item 3 is', shoplist[3]) print('Item -1 is', shoplist[-1]) print('Item -2 is', shoplist[-2]) # Slicing on a list print('Item 1 to 3 is', shoplist[1:3]) print('Item 2 to end is', shoplist[2:]) print('Item 1 to -1 is', shoplist[1:-1]) print('Item start to end is', shoplist[:]) # Slicing on a string name = 'swaroop' print('characters 1 to 3 is', name[1:3]) print('characters 2 to end is', name[2:]) print('characters 1 to -1 is', name[1:-1]) print('characters start to end is', name[:])
以上代码运行后的输出结果如下:
Item 0 is pidancode.com
Item 1 is baidu.com
Item 2 is google.com
Item 3 is bandao.cn
Item -1 is bandao.cn
Item -2 is google.com
Item 1 to 3 is ['baidu.com', 'google.com']
Item 2 to end is ['google.com', 'bandao.cn']
Item 1 to -1 is ['baidu.com', 'google.com']
Item start to end is ['pidancode.com', 'baidu.com', 'google.com', 'bandao.cn']
characters 1 to 3 is wa
characters 2 to end is aroop
characters 1 to -1 is waroo
characters start to end is swaroop
相关文章