Skip to content

运算符

运算符描述支持的容器类型
+合并字符串、列表、元组
*复制字符串、列表、元组
in元素是否存在字符串、列表、元组、字典
not in元素是否不存在字符串、列表、元组、字典

+

python
# 1. 字符串 
>>> str1 = 'aa'
>>> str2 = 'bb'
>>> str3 = str1 + str2
>>> str3
'aabb'


# 2. 列表 
>>> list1 = ['a', 'b']
>>> list2 = ['c', 'd']
>>> list3 = list1 + list2
>>> list3
['a', 'b', 'c', 'd']


# 3. 元组 
>>> t1 = ('a', 'b')
>>> t2 = ('c', 'd')
>>> t3 = t1 + t2
>>> t3
('a', 'b', 'c', 'd')

*

python
# 1. 字符串
>>> print('-' * 10)
----------

# 2. 列表
>>> list1 = ['hello']
>>> print(list1 * 4)
['hello', 'hello', 'hello', 'hello']

# 3. 元组
>>> t1 = ('world',)
>>> print(t1 * 4)
('world', 'world', 'world', 'world')

in 或 not in

python
# 1. 字符串
>>> print('a' in 'abcd') 
True
>>> print('a' not in 'abcd') 
False


# 2. 列表
>>> list1 = ['a', 'b', 'c', 'd']
>>> print('a' in list1)
True
>>> print('a' not in list1)
False


# 3. 元组
>>> t1 = ('a', 'b', 'c', 'd')
>>> print('aa' in t1)
False
>>> print('aa' not in t1)
True

公共方法

函数描述
len()计算容器中元素个数
del 或 del()删除
max()返回容器中元素最大值
min()返回容器中元素最小值
range(start, end, step)生成从start到end的数字,步长为 step,供for循环使用
enumerate()函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

len()

python
# 1. 字符串
>>> str1 = 'abcdefg'
>>> print(len(str1))
7

# 2. 列表
list1 = [10, 20, 30, 40]
print(len(list1))

# 3. 元组
>>> list1 = [10, 20, 30, 40]
>>> print(len(list1))
4

# 4. 集合
>>> s1 = {10, 20, 30}
>>> print(len(s1))
3

# 5. 字典
>>> dict1 = {'name': 'Rose', 'age': 18}
>>> print(len(dict1))
2

del()

python
# 1. 字符串
>>> str1 = 'abcdefg'
>>> del str1
>>> print(str1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'str1' is not defined. Did you mean: 'str2'?


# 2. 列表
>>> list1 = [10, 20, 30, 40]
>>> del(list1[0])
>>> print(list1)
[20, 30, 40]

range()

python
>>> for i in range(1, 5, 1):
...     print(i)
...
1
2
3
4


>>> for i in range(1, 5, 2):
...     print(i)
...
1
3

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4

注意:range()生成的序列不包含end数字。

max()

python
# 1. 字符串
>>> str1 = 'abcdefg'
>>> print(max(str1))
g


# 2. 列表
>>> list1 = [10, 20, 30, 40]
>>> print(max(list1))
40

min()

python
# 1. 字符串
>>> str1 = 'abcdefg'
>>> print(min(str1))
a

# 2. 列表
>>> list1 = [10, 20, 30, 40]
>>> print(min(list1))
10

enumerate()

  • 语法
python
enumerate(可遍历对象, start=0)

enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

注意:start参数用来设置遍历数据的下标的起始值,默认为0。

  • 快速体验
python
list1 = ['a', 'b', 'c', 'd', 'e']

for i in enumerate(list1):
    print(i)

for index, char in enumerate(list1, start=1):
    print(f'下标是{index}, 对应的字符是{char}')

运行结果:

python
>>> list1 = ['a', 'b', 'c', 'd', 'e']
>>> for i in enumerate(list1):
...     print(i)
...
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
(4, 'e')

>>> for index, char in enumerate(list1, start=1):
...     print(f'下标是{index}, 对应的字符是{char}')
...
下标是1, 对应的字符是a
下标是2, 对应的字符是b
下标是3, 对应的字符是c
下标是4, 对应的字符是d
下标是5, 对应的字符是e