表示组的方式
一、列表<list>
1.定义
[1,2,3,4,5,6]
print(type([1,2,3,4,5,6]))
运行结果:
<class 'list'>
注:列表中的元素可以不是固定的一种类型,如:
["hello","你好",1,'a',0]
[[1,2],[3,4,5],[True,False]](此列表又叫做嵌套列表)
2.基本操作
2.1查找,与字符串的查找方法一样
["hello","world","你好","很高兴认识你"][0] = "hello"
["hello","world","你好","很高兴认识你"][-1] = "很高兴认识你"
2.2截取,与字符串的截取方法一样
["hello","world","你好","很高兴认识你"][1:3] = ["world","你好"]
["hello","world","你好","很高兴认识你"][1:-1] = ["world","你好"]
["hello","world","你好","很高兴认识你"][1:] = ["world","你好","很高兴认识你"]
["hello","world","你好","很高兴认识你"][:2] = ["hello","world"]
["hello","world","你好","很高兴认识你"][2:100] = ["你好","很高兴认识你"]
注:列表的使用一个数字查找时得到的结果类型是该元素的类型,若使用[a:b]的方法截取得的类型仍是一个列表
print(type([1,2,'a',True][2]))
print(type(["hello","world","你好","很高兴认识你"][2:3]))
运行结果:
<class 'str'>
<class 'list'>
2.3相加
[1,2,'a'] + [True, 'b'] = [1,2,'a',True,'b']
2.4相乘,只能和整数相乘
[1,2,'a'] * 3 = [1, 2, 'a', 1, 2, 'a', 1, 2, 'a']
2.5列表不能相减,会报错
print([1,2,3,'a'] - ['a'])
报错提示:
TypeError: unsupported operand type(s) for -: 'list' and 'list'
二、元组<tuple>
2.1 基本操作
元组的查找、截取、相加、相乘的操作与列表一样
元组与列表的区别:两种类型除了字面上的区别(括号与方括号)之外,最重要的一点是tuple是不可变类型,大小固定,而 list 是可变类型、数据可以动态变化,这种差异使得两者提供的方法、应用场景、性能上都有很大的区别。
2.2 type类型
type((1)) = int
当小括号里只有一个元素时,会将这个小括号做为运算符的括号来处理,而不是元组的小括号
type(()) = tuple
可以用一对空括号来表示元组
type((1,)) = tuple
三、str、list、tuple由组引出,叫做序列,序列可以+、*
[ : ]叫做切片
几个常用的方法:
判断某序列是否有某元素:3 in [1,2,3,4] = True
判断某序列没有某元素:3 not in [1,2,3,4] = False
输出序列的长度:len()
输出序列的最大值:max()
输出序列的最小值:min()
将字母转换为ASCII码:ord()
注:使用max()与min()方法时,序列中的元素类型应一致,如max([1,2,3,4])
print(max((1,2,True,'a')))会报错:
TypeError: '>' not supported between instances of 'str' and 'int'