Python中“组”的概念与意义
一、列表的定义
>>> type([1,2,3,4,5,6])
<class 'list'>
>>> type(["hello", "world", 1, 9])
<class 'list'>
# 嵌套列表
>>> type([[1, 2], [3, 4], [True, False]])
<class 'list'>
二、列表的基本操作
1、获取列表元素:
>>> skill_list = ["新月打击", "苍白之瀑布", "月之降临", "月神冲刺"]
>>> skill_list[0]
'新月打击'
>>> skill_list[3]
'月神冲刺'
>>> skill_list[0:2]
['新月打击', '苍白之瀑布']
>>> skill_list[-1:]
['月神冲刺']
2、修改列表元素:
>>> skill_list = (["新月打击", "苍白之瀑布", "月之降临", "月神冲刺"] + ["点燃", "虚弱"])
>>> skill_list
['新月打击', '苍白之瀑布', '月之降临', '月神冲刺', '点燃', '虚弱']
>>> ["点燃", "虚弱"] * 3
['点燃', '虚弱', '点燃', '虚弱', '点燃', '虚弱']
三、元祖
>>> (1, 2, 3, 4, 5) >>> (1, '-1', True)
(1, 2, 3, 4, 5) (1, '-1', True)
>>> (1, 2, 3, 4)[0] >>> (1, 2, 3, 4)[0:2]
1 (1, 2)
>>> (1, 2, 3) + (4, 5, 6) >>> (1, 2, 3) * 3
(1, 2, 3, 4, 5, 6) (1, 2, 3, 1, 2, 3, 1, 2, 3)
>>> type((1)) >>> type(('hello'))
<class 'int'> <class 'str'>
>>> type((1,)) >>> type(("hello",))
<class 'tuple'> <class 'tuple'>
四、序列总结
序列:str、list、tuple
ord:将字母转换为ascii(对字符串进行排序,求最大值,求最小值,其原理是对字符串对应ascii的操作)
>>> ord('w')
119
>>> ord('d')
100
>>> ord(' ')
32
>>> sorted('hello world')
[' ', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
>>> max('hello world')
'w'
>>> min('hello world')
' '
五、set集合
1、集合是无序的;
>>> type({1, 2, 3, 4, 5, 6})
<class 'set'>
>>> {1, 2, 3, 4, 5, 6}[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'set' object does not support indexing
>>> {1, 2, 3, 4, 5, 6}[0:2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'set' object is not subscriptable
2、集合元素是不重复的;
>>> {1, 1, 2, 2, 3, 3, 4, 4}
{1, 2, 3, 4}
3、集合长度len();
>>> len({1, 2, 3})
3
4、集合in 与 not in;
>>> 1 in {1, 2, 3}
True
>>> 1 not in {1, 2, 3}
False
5、求两个集合的差集;
>>> {1, 2, 3, 4, 5, 6} - {3, 4}
{1, 2, 5, 6}
6、求两个集合的交集;
>>> {1, 2, 3, 4, 5, 6} & {3, 4}
{3, 4}
7、求两个集合的并集;
>>> {1, 2, 3, 4, 5, 6} | {3, 4, 7}
{1, 2, 3, 4, 5, 6, 7}
8、定义空集合。
>>> type({})
<class 'dict'>
>>> type(set())
<class 'set'>
>>> len(set())
0