为了账号安全,请及时绑定邮箱和手机立即绑定

Python课程笔记 第4章 Python中表示“组”的概念与定义

标签:
Python

4-1 列表的定义

type([1,2,3,4,5,6])
<class 'list'>
type(['hello',1,2,3,True])
<class 'list'>

4-2 列表的基本操作
从列表中获取元素

['hello',1,2,True,'world'][0]
'hello'
['hello',1,2,True,'world'][3]
True
['hello',1,2,True,'world'][0:2]
['hello', 1]
['hello','world','hi'][-1:]
['hi']

加法

['hello']+['world']
['hello', 'world']

乘法

['hello']*3
['hello', 'hello', 'hello']

4-3 元组
()代表元组

(1,2,3,4,5)[0]
1
加法
(1,2,3)+(4,5,6)
(1, 2, 3, 4, 5, 6)
乘法
(1,2,3)*3
(1, 2, 3, 1, 2, 3, 1, 2, 3)
tuple代表元组类型
type((1,2,3))
<class 'tuple'>

4-4 序列总结

type((1))
<class 'int'>
type(('hello'))
<class 'str'>
(1+1)*2
4
Python不知道(1)是元组还是运算
type((1,))
<class 'tuple'>
type(())
<class 'tuple'>

序列:str,list,tuple
共有操作:
序列里的每一个元素都有一个序号
切片操作[1,2,3,4,5][0:3]
序列可以+,*

'hello world'[2]
'l'
[1,2,3][2]
3
(1,2,3)[2]
3

判断某元素是否在序列里

3 in [1,2,3,4,5]
True
10 in [1,2,3,4,5]
False
3 not in [1,2,3,4,5]
False
10 not in [1,2,3,4,5]
True

求序列的长度

len([1,2,3,4,5])
5
len('hello world')
11

求序列最大值最小值

max([1,2,3,4,5])
5
min([1,2,3,4,5])
1
max('abcdefg')
'g'
min('abcdefg')
'a'
如果string中有空格,最最小值为空格

ord将字母转换成ascll码(电脑储存的码)

ord(' ')
32
ord('w')
119
ord('d')
100

4-5 set集合
集合无序
集合{}

type({1,2,3,4,5})
<class 'set'>
{1,2,3,4,5,6}[0]
Traceback (most recent call last):
File "<pyshell#33>", line 1, in <module>
{1,2,3,4,5,6}[0]
TypeError: 'set' object does not support indexing
因为集合无序,所以没有下标索引,切片操作

集合的不重复性

{1,1,2,3,4,4,4}
{1, 2, 3, 4}

集合可以判断长度和某个元素是否在集合里面

len({1,2,3})
3
3 in {1,2,3}
True

集合可以进行减法运算,代表集合差集运算

{1,2,3,4,5}-{1,2}
{3, 4, 5}

两个集合的交集&

{1,2,3,4,5,6}&{3,4}
{3, 4}

两个集合的并集 |

{1,2,3,4,5,6} | {3,4,7}
{1, 2, 3, 4, 5, 6, 7}

空集合表示:set(),不是{}

type(set())
<class 'set'>
type({})
<class 'dict'>

4-6 dict字典
字典有很多个key和value,集合类型

{key1:value1,key2:value2}
type({1:1,2:2,3:3})
<class 'dict'>

通过key来访问value
{'q':'新月','w':'苍白','e':'太阳'}['q']
'新月'
字典不可以有重复的key
数字1和字符串1不算相同的key

{1:'新月','1':'苍白','e':'太阳'}[1]
'新月'
{1:'新月','1':'苍白','e':'太阳'}['1']
'苍白'
value: str int float list set dict
key:必须是不可变类型str int tuple
{(1,2):'新月','1':'苍白','e':'太阳'}

{}代表空的字典

4-7 思维导图总结基本数据类型
字符串和元组是不可变类型

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消