序列是一种可迭代的、有序的、可以包含重复元素的数据结构。
不可变序列(Immutable Sequence):字符串(class str
)、元组(class tuple
)、字节串(class bytes
)、范围(class range
)。
可变序列(Mutable Sequence):列表(class list
)、字节数组(class bytearray
)。
1.字符串(str)
>>> a = "Hello"
>>> a[0]
'H'
>>> a[1]
'e'
>>> a[4]
'o'
>>> a[-1]
'o'
>>> a[-2]
'l'
2.元组(tuple)
创建元组可以使用tuple([iterable])或者圆括号用逗号“ , ”将元素分隔。
#圆括号创建法
>>> a = ('hello', 'world' ,1,2,3)
>>> a[1]
'world'
#tuple()创建法
a = tuple(['hello', 'world', 1,2,3])
#空元组
a = ()
3.范围(range)
创建范围可以使用range()函数。范围包括start位置元素,不包括end位置元素。
#如果省略 step 参数,其默认值为 1。 如果省略 start 参数,其默认值为 0
range(start, stop[, step])
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]
4.列表(list)
创建列表可以使用list([iterable])或者方括号用逗号“ , ”将元素分隔。
#方括号创建法
>>> a = ['hello', 'world', 1,2,3]
>>> a[1]
'world'
#list()创建法
a = list(('hello', 'world', 1,2,3]))
#空列表
a = []
原创文章,作者:huoxiaoqiang,如若转载,请注明出处:https://www.huoxiaoqiang.com/python/pythonlang/2699.html