(更新时间)2021年3月21日 python基础知识(容器

编程入门 行业动态 更新时间:2024-10-06 04:08:27

(<a href=https://www.elefans.com/category/jswz/34/1764326.html style=更新时间)2021年3月21日 python基础知识(容器"/>

(更新时间)2021年3月21日 python基础知识(容器

公共方法

1. 运算符

运算符Python 表达式结果描述支持的数据类型
+[1, 2] + [3, 4][1, 2, 3, 4]合并字符串、列表、元组
*[‘Hi!’] * 4[‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’]复制字符串、列表、元组
in3 in (1, 2, 3)True元素是否存在字符串、列表、元组、字典
not in4 not in (1, 2, 3)True元素是否不存在字符串、列表、元组、字典

+

>>> "hello " + "itcast"
'hello itcast'
>>> [1, 2] + [3, 4]
[1, 2, 3, 4]
>>> ('a', 'b') + ('c', 'd')
('a', 'b', 'c', 'd')

*

>>> 'ab' * 4
'ababab'
>>> [1, 2] * 4
[1, 2, 1, 2, 1, 2, 1, 2]
>>> ('a', 'b') * 4
('a', 'b', 'a', 'b', 'a', 'b', 'a', 'b')

in

>>> 'itc' in 'hello itcast'
True
>>> 3 in [1, 2]
False
>>> 4 in (1, 2, 3, 4)
True
>>> "name" in {"name":"Delron", "age":24}
True

注意,in在对字典操作时,判断的是字典的键

2. python内置函数

Python包含了以下内置函数

序号方法描述
1len(item)计算容器中元素个数
2max(item)返回容器中元素最大值
3min(item)返回容器中元素最小值
4del(item)删除变量

len

>>> len("hello itcast")
12
>>> len([1, 2, 3, 4])
4
>>> len((3,4))
2
>>> len({"a":1, "b":2})
2
注意:len在操作字典数据时,返回的是键值对个数。

max

>>> max("hello itcast")
't'
>>> max([1,4,522,3,4])
522
>>> max({"a":1, "b":2})
'b'
>>> max({"a":10, "b":2})
'b'
>>> max({"c":10, "b":2})
'c'

del

del有两种用法,一种是del加空格,另一种是del()

>>> a = 1
>>> a
1
>>> del a
>>> a
Traceback (most recent call last):File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> a = ['a', 'b']
>>> del a[0]
>>> a
['b']
>>> del(a)
>>> a
Traceback (most recent call last):File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

3. 多维列表/元祖访问的示例

>>> tuple1 = [(2,3),(4,5)]
>>> tuple1[0]
(2, 3)
>>> tuple1[0][0]
2
>>> tuple1[0][2]
Traceback (most recent call last):File "<stdin>", line 1, in <module>
IndexError: tuple index out of range>>> tuple1[0][1]
3
>>> tuple1[2][2]
Traceback (most recent call last):File "<stdin>", line 1, in <module>
IndexError: list index out of range>>> tuple2 = tuple1+[(3)]
>>> tuple2
[(2, 3), (4, 5), 3]
>>> tuple2[2]
3
>>> tuple2[2][0]
Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: 'int' object is not subscriptable

更多推荐

(更新时间)2021年3月21日 python基础知识(容器

本文发布于:2024-02-13 13:42:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1758544.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:更新时间   容器   基础知识   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!