新手运算符不知道啥?冠希哥手把手教你python运算符知识!

运算符

运算符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

'abababab'

>>> [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在对字典操作时,判断的是字典的键

python内置函数

Python包含了以下内置函数

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

cmp

>>> cmp("hello", "itcast")

-1

>>> cmp("itcast", "hello")

1

>>> cmp("itcast", "itcast")

0

>>> cmp([1, 2], [3, 4])

-1

>>> cmp([1, 2], [1, 1])

1

>>> cmp([1, 2], [1, 2, 3])

-1

>>> cmp({"a":1}, {"b":1})

-1

>>> cmp({"a":2}, {"a":1})

1

>>> cmp({"a":2}, {"a":2, "b":1})

-1
注意:cmp在比较字典数据时,先比较键,再比较值。

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
多维列表/元祖访问的示例
>>> 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

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值