0
点赞
收藏
分享

微信扫一扫

【Class 3】 Python 基础二


列表 list [ ]

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

列表也可以参杂字符串或者其他数据类型数据
>>> type(["hello",1,"i",2,"am",3,"handsome",4,5, True, False])
<class 'list'>
>>> print(["hello",1,"i",2,"am",3,"handsome",4,5, True, False])
['hello', 1, 'i', 2, 'am', 3, 'handsome', 4, 5, True, False]
>>>

嵌套列表:列表内部元素也可以是列表
格式:[[ ],[ ],[ ],[ ]]
>>> type([[1,2],[True,False],[1,"Ciellee"]])
<class 'list'>

访问列表: [x,x,x][n]
>>> ["其疾如风","其徐如林","侵掠如火","不动如山"][1]
'其徐如林'
>>> ["其疾如风","其徐如林","侵掠如火","不动如山"][-1]
'不动如山'
>>> ["其疾如风","其徐如林","侵掠如火","不动如山"][0:2]
['其疾如风', '其徐如林']
>>> ["其疾如风","其徐如林","侵掠如火","不动如山"][-2:]
['侵掠如火', '不动如山']

列表的操作运算: []+[]
>>> ["其疾如风","其徐如林"]+["侵掠如火","不动如山"]
['其疾如风', '其徐如林', '侵掠如火', '不动如山']
>>>
>>> ["其疾如风","其徐如林"]*3
['其疾如风', '其徐如林', '其疾如风', '其徐如林', '其疾如风', '其徐如林']

元组 tuple ( )

>>> (1,2,3,4,True)    
(1, 2, 3, 4, True)
>>> (1,2,3,4,True)[2]
3
>>> (1,2,3,4,True)[-1]
True

>>> (1,2,3,4,True)+(False,1)
(1, 2, 3, 4, True, False, 1)

元组和小阔号的区别

注意,元组只有一个元素的时候,需要加个逗号 和 小括号区分开来,表明是元组

括号内不带都逗号是整形int, 带逗号是元组tuple
>>> type((1))
<class 'int'>
>>> type((1,))
<class 'tuple'>

当表示空的元组的时候,不需要加都要,空括号就可以了
>>> type((,))
SyntaxError: invalid syntax
>>> type(())
<class 'tuple'>
>>>

实例:
>>> (1,2,3,4,True)+(False,)
(1, 2, 3, 4, True, False)
报错如下:
>>> (1,2,3,4,True)+(False)
Traceback (most recent call last):
File "<pyshell#179>", line 1, in <module>
(1,2,3,4,True)+(False)
TypeError: can only concatenate tuple (not "bool") to tuple

序列

字符串str,列表list,元组tuple 其实都可以当成一种序列,序列都是有序的。

集合set 是无序的。

切片

>>> [1,2,3,4,5,6,7,8][3:7]
[4, 5, 6, 7]
>>> "abcdefg"[3:6]
'def'
>>> ('a','b',2,'c',3,'d',4,5)[2:6]
(2, 'c', 3, 'd')

查找元素是否在序列中 in / not in

>>> 3 in [1,2,3]
True
>>> 5 in [1,2,3]
False

>>> 3 not in [1,2,3]
False
>>> 5 not in [1,2,3]
True

>>> 3 in (1,2,3)
True

>>> 'b' in "abcdefg"
True
>>> 'z' in "abcdefg"
False
>>> 'b' not in "abcdefg"
False

获取序列的长度 len([ ])

>>> len([2,3,4,5,6])
5
>>> len((2,3,4,5,6))
5
>>> len("ciellee is handsome")
19
>>>

求最大,最小值

>>> max([1,2,3,4,5,6])
6
>>> min([1,2,3,4,5,6])
1

>>> max("abcdefghijklmn")
'n'
>>> min("abcdefghijklmn")
'a'

求字符的ASCII 码函数 ord()
>>> ord('a')
97



举报

相关推荐

0 条评论