Python可迭代对象

可迭代对象

可以用for…in…这类语句迭代读取一条数据供我们使用的对象称为可迭代对象

  • int、float、bool称为不可迭代对象
  • str、list、tuple、set、dict称为可迭代对象
  • 可以用isinstance()判断是否是可迭代对象
    • 格式:isinstance(obj, Iterable)
    • 返回值:bool类型
# 可迭代对象案例
from collections import Iterable

a = int()
b = float()
c = bool()
d = str()
e = list()
f = tuple()
g = set()
h = dict()

print(isinstance(a, Iterable))
print(isinstance(b, Iterable))
print(isinstance(c, Iterable))
print(isinstance(d, Iterable))
print(isinstance(e, Iterable))
print(isinstance(f, Iterable))
print(isinstance(g, Iterable))
print(isinstance(h, Iterable))

"""
运行结果:
False
False
False
True
True
True
True
True
"""

列表(list)

一组有顺序的数据的组合

  • 列表中的元素有先后顺序
  • 列表中的元素可以是不同类型的
  • 列表用“[]”包含
# list案例1
l1 = [1, 2, 3, 'Hello', 'World']
l2 = list()
l3 = []

print(type(l1))
print(l1)
print(type(l2))
print(l2)
print(type(l3))
print(l3)

"""
运行结果:

[1, 2, 3, 'Hello', 'World']

[]

[]
"""
# list案例2
s = 'Mad man'

l1 = list(s)
l2 = [s]

print(type(l1))
print(l1)
print(type(l2))
print(l2)

"""
运行结果:

['M', 'a', 'd', ' ', 'm', 'a', 'n']

['Mad man']
"""

列表的常见操作

访问

  • 使用下标操作,也叫索引
  • 格式:list[index]
  • 列表的元素索引从0开始
  • 索引超过列表范围会报错
# 列表访问案例
l1 = [1, 2, 3, 4, 5]

print(l1[2])
print(l1[100])

"""
运行结果:
3
IndexError: list index out of range
"""

切片

对列表进行任意一段的截取

  • 使用下标操作,也叫索引
  • 左索引包括,右索引不包括
  • 格式:list[index1: index2: step]
    • index1:左索引,可以为空,默认为方向上的起点
    • index2:右索引,可以为空,默认为方向上的终点
    • step:步长,默认为1,如果是负数,则方向从右往左
  • 左右索引都为空时,默认包含整个列表
  • 列表最后一个数据的索引是-1
  • 切片后生成的列表是一个全新的列表
# 列表切片案例1
l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
l2 = l1[0: 9]
l3 = l1

print(id(l1))
print(l1)
print(id(l2))
print(l1)
print(id(l3))
print(l3)

"""
运行结果:
2290380530184
[1, 2, 3, 4, 5, 6, 7, 8, 9]
2290380530248
[1, 2, 3, 4, 5, 6, 7, 8, 9]
2290380530184
[1, 2, 3, 4, 5, 6, 7, 8, 9]
"""
# 列表切片案例2
l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(l[:4])
print(l[4:])
print(l[:])

"""
运行结果:
[1, 2, 3, 4]
[5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
"""
# 列表切片案例3
l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(l[::])
print(l[::2])

"""
运行结果:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 3, 5, 7, 9]
"""
  • 索引可以超出范围,超出后不再考虑多余索引内容
# 列表切片案例4
l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(l[:100])

"""
运行结果:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
"""
  • 索引值可以为负数
    • 索引值为负数时,表示顺序从右往左
    • 列表的最后一个元素索引值为-1
  • 注意:列表访问的默认顺序是从左往右
# 列表切片案例5
l = [1, 2, 3, 4, 5, 6, 7, 8, 9]

print(l[-2:-5])
print(l[-2:-5:-1])
print(l[-5:-2])

"""
运行结果:
[]
[8, 7, 6]
[5, 6, 7]
"""

加法和乘法

  • 加法操作用操作符“+
  • 乘法操作用操作符“*
# 列表的加法乘法操作
l1 = [1, 2, 3]
l2 = ['one', 'two', 'three']
l3 = l1 + l2

print(l3)
print(l3 * 2)

"""
运行结果:
[1, 2, 3, 'one', 'two', 'three']
[1, 2, 3, 'one', 'two', 'three', 1, 2, 3, 'one', 'two', 'three']
"""

成员检测

  • 用“in”和“not in
  • 返回值是一个布尔值
# 列表的成员检测案例
l = ['I', 'am', 'madman', 1, 2, 3]

if 'madman' in l:
    print('在!')
if 4 not in l:
    print('不在!')
    
"""
运行结果:
在!
不在!
"""

嵌套

  • 列表可以嵌套操作
  • 可以用多层循环或单层循环访多层嵌套的内容
#  列表嵌套案例
l = [[1, 2, 3], [4, 5, 6]]

# 多层循环访问
for i in l:
    print(i)
    for j in i:
        print(j)
        
# 单层循环访问
for i, j, k in l:
    print(i, j, k)
        
 """
 运行结果:
[1, 2, 3]
1
2
3
[4, 5, 6]
4
5
6
1 2 3
4 5 6
 """

生成式

  • 可用生成式更便利地生成集合
  • 格式:[i for i in list if xxx]
# 列表生成式案例
l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
l2 = [2, 3]
l3 = [i for i in l1]
l4 = [i for i in l1 if i % 2 == 0]
l5 = [i**2 for i in l1]
l6 = [m*n for m in l1 for n in l2]
l7 = [i for i in range(0, 11)]

print(l3)
print(l4)
print(l5)
print(l6)
print(l7)

"""
运行结果:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 4, 6, 8]
[1, 4, 9, 16, 25, 36, 49, 64, 81]
[2, 3, 4, 6, 6, 9, 8, 12, 10, 15, 12, 18, 14, 21, 16, 24, 18, 27]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
"""

删除

可以删除指定的内容

  • 格式:del list/list[index]
# 列表删除案例
l = [1, 2, 3, 4]

del l[1]
print(l)

del l[0: 2]
print(l)

del l
print(l)

"""
运行结果:
[1, 3, 4]
[4]
NameError: name 'l' is not defined
"""

列表的常用函数

  • len:求列表长度:len(list)
  • max:求列表中的最大值:max(list)
  • min:求列表中的最小值:min(list)
  • list:将其他格式的数据转换成list:list(object)
  • append:在末尾追加内容:list.append(value)
  • insert:在任何位置插入内容:insert(index, value),如果没有那个索引会报错
  • pop:对可变序列中元素索引进行检索删除,默认索引为-1返回删除值:list.pop(index)
  • remove:直接对可变序中的元素进行检索删除,返回的是删除后的列表,不返回删除值,如果没有那个值会报错:list.remove(index)
  • clear:清空列表:list.clear()
  • reverse:翻转:list.reverse()
  • extend:扩展列表,在A列表后面拼接B列表:listA.extend(listB)
  • count:查找列表中指定值或元素的个数并返回:list.count(value)
  • copy:浅拷贝:list.copy()
  • index:查找元素所在下标:list.index(value)
  • sort:按照ASCII顺序进行排序:list.sort()

元组(tuple)

可以理解成一个不允许更改的列表

  • 元组中的元素不可修改,但是元组本身可以改变
  • 元组中的元素有先后顺序
  • 元组中的元素可以是不同类型的
  • 元组用“()”包含
  • 注意:创建只有一个元素的元组时,要在第一个元素后面加逗号
# tuple案例
t1 = ()
t2 = tuple()
t3 = (100)
t4 = (100,)
t5 = 100,
t6 = 100, 200

print(type(t1))
print(t1)
print(type(t2))
print(t2)
print(type(t3))
print(t3)
print(type(t4))
print(t4)
print(type(t5))
print(t5)
print(type(t6))
print(t6)

"""
运行结果:

()

()

100

(100,)

(100,)

(100, 200)
"""

元组的常见操作

元组的常见操作和列表类似

  • 元组的内容不可以更改
  • 元组无法使用生成式
# 元组的访问切片案例
t = ('I', 'am', 'Madman')

# 访问操作
print(t)
print(t[2])
print(t[100])

# 切片操作
print(t[:])
print(t[-1::-1])
print(t[::-1])

"""
运行结果:
('I', 'am', 'Madman')
Madman
IndexError: tuple index out of range
('I', 'am', 'Madman')
('Madman', 'am', 'I')
('Madman', 'am', 'I')
"""
# 元组的加法乘法案例
t1 = 1, 2, 3
t2 = 'I', 'am', 'madman'
t3 = t1 + t2
print(type(t3))
print(t3)

t4 = t3 * 2
print(type(t4))
print(t4)

"""
运行结果:

(1, 2, 3, 'I', 'am', 'madman')

(1, 2, 3, 'I', 'am', 'madman', 1, 2, 3, 'I', 'am', 'madman')
"""
# 元组的in和not in案例
t = (1, 2, 3)
if 1 in t:
    print('在!')
if 4 not in t:
    print('不在!')
    
"""
运行结果:
在!
不在!
"""
# 元组的循环访问案例
t = ([1, 2, 3], [4, 5], (7, 8, 9))

# 多层循环访问
for i in t:
    print(i)
    for j in i:
        print(j)
print('*' * 20)

# 单层循环访问,i, j, k要和元组的元素个数对应,否则报错
for i, j, k in t:
    print(i, j, k)

"""
运行结果:
[1, 2, 3]
1
2
3
[4, 5]
4
5
(7, 8, 9)
7
8
9
********************
1 2 3   
ValueError: not enough values to unpack (expected 3, got 2)
"""
# 元组生成式案例
t1 = (1, 2, 3, 4, 5, 6, 7, 8, 9)
t2 = (2, 3)
t3 = (i for i in t1)
t4 = (i for i in t1 if i % 2 == 0)
t5 = (i**2 for i in t1)
t6 = (m*n for m in t1 for n in t2)
t7 = (i for i in range(0, 11))

print(t3)
print(t4)
print(t5)
print(t6)
print(t7)

"""
运行结果:
 at 0x0000029E8CC8C390>
 at 0x0000029E8CC8C5E8>
 at 0x0000029E8CC8C660>
 at 0x0000029E8CC8C6D8>
 at 0x000002A6B320C7C8>
"""
# 元组的删除案例
t = (1, 2, 3, 4, 5)

# 因为元组的内容不可以改变,所以删除内容会报错
del t[1]
print(t)

del t[0: 2]
print(t)

del t
print(t)

"""
TypeError: 'tuple' object does not support item deletion
TypeError: 'tuple' object does not support item deletion
NameError: name 't' is not defined
"""

集合(set)

没有顺序且没有重复元素的一组数据

  • 集合中的元素不重复
  • 集合中的元素没有固定的顺序
  • 集合中的元素可以是不同类型的
  • 元组用“{}”包含
  • 注意
    • 集合内部只可以存放可哈希数据
    • 可哈希:生命周期内不可改变值的对象(str、int、float、tuple、对象集object等)
    • 不可哈希类型:list、set、dict
# set案例
s1 = {}
s2 = set()
s3 = {1, 2, 3, 'I', 'am', 'madman', (1, 2, 3)}
s4 = {1, 2, 3, [1, 2, 3]}
s5 = {1, 2, 3, ([1, 2, 3], [4, 5, 6])}
s6 = {1, 2, 3, {1, 2, 3}}
s7 = {1, 2, 3, ({1, 2, 3}, {4, 5, 6})}

print(type(s1))
print(s1)
print(type(s2))
print(s2)
print(type(s3))
print(s3)
print(type(s4))
print(s4)
print(type(s5))
print(s5)
print(type(s6))
print(s6)
print(type(s7))
print(s7)

"""
运行结果:

{}

set()

{1, 2, 3, 'I', (1, 2, 3), 'madman', 'am'}
TypeError: unhashable type: 'list'
TypeError: unhashable type: 'list'
TypeError: unhashable type: 'set'
TypeError: unhashable type: 'set'
"""

集合的常见操作

集合的常见操作类似列表

  • 集合不可进行访问切片操作
  • 集合不可进行加法乘法操作
# 集合的访问切片案例
s = {1, 2, 3, 4, 5, 6}

print(s[1])
print(s[0: 4])

"""
运行结果:
TypeError: 'set' object does not support indexing
TypeError: 'set' object is not subscriptable
"""
# 集合的加法乘法案例
s1 = {1, 2, 3}
s2 = {'I', 'am', 'madman'}
s3 = s1 + s2 
print(type(s3))
print(s3)

s4 = s1 * 2
print(type(s4))
print(s4)

"""
运行结果:
TypeError: unsupported operand type(s) for +: 'set' and 'set'
TypeError: unsupported operand type(s) for *: 'set' and 'int'
"""
# 集合的in和not in操作
s = {1, 2, 3, 4, 'Madman', (1, 2, 3)}

if (1, 2, 3) in s:
    print('在!')
if 'madman' not in s:
    print('不在!')
    
"""
运行结果:
在!
不在!
"""
# 集合的循环访问案例
s1 = {1, 2, 3, 4, 5, 6, (1, 2, 3), (4, 5, 6)}
s2 = {(1, 2, 3), (4, 5, 6), (1, 2, 3)}
s3 = {(1, 2, 3), (4, 5, 6), (1, 2)}

for i in s1:
    print(i)
for i, j, k in s2:
    print(i, j, k)
for i, j, k in s3:
    print(i, j, k)
    
"""
运行结果:
1
2
3
4
5
6
(1, 2, 3)
(4, 5, 6)
4 5 6
1 2 3
ValueError: not enough values to unpack (expected 3, got 2)
"""
# 集合的生成式案例
s1 = {1, 2, 3, 4, 5, 6, 7, 8, 9}
s2 = {2, 3}
s3 = {i for i in s1}
s4 = {i for i in s1 if i % 2 == 0}
s5 = {i**2 for i in s1}
s6 = {m*n for m in s1 for n in s2}
s7 = {i for i in range(0, 11)}

print(s3)
print(s4)
print(s5)
print(s6)
print(s7)

"""
运行结果:
{1, 2, 3, 4, 5, 6, 7, 8, 9}
{8, 2, 4, 6}
{64, 1, 4, 36, 9, 16, 49, 81, 25}
{2, 3, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 21, 24, 27}
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
"""
# 集合的删除案例
s = {1, 2, 3, 4}

del s[2]
print(s)

del s
print(s)

"""
运行结果:
TypeError: 'set' object doesn't support item deletion
NameError: name 's' is not defined
"""

集合的数学操作

  • intersection():交集
    • 格式:set1.intersection(set2)
    • 返回值:计算结果,set类型
  • difference():差集
    • 格式:set1.difference(set2)
    • 返回值:计算结果,set类型
    • 可以用“-”号表示
  • union():并集
    • 格式:set1.union(set2)
    • 返回值:计算结果,set类型
# 集合的数学操作案例1
s1 = {1, 2, 3, 4}
s2 = {3, 4, 5, 6}

print(s1.intersection(s2))
print(s1.difference(s2))
print(s1 - s2)
print(s1.union(s2))
print(s1 + s2)

"""
运行结果:
{3, 4}
{1, 2}
{1, 2}
{1, 2, 3, 4, 5, 6}
TypeError: unsupported operand type(s) for +: 'set' and 'set'
"""
  • issubset:检查一个集合是否为另一个集合的子集
    • 格式:set1.issubset(set2)
    • 返回值:布尔值
  • issuperset:检查一个集合是否为另一个集合的超集
    • 格式:set1.issuperset(set2)
    • 返回值:布尔值
# 集合的数学操作案例2
s1 = {1, 2, 3}
s2 = {1, 2, 3, 4}

print(s1.issubset(s2))
print(s2.issuperset(s1))

"""
运行结果:
True
True
"""

frozenset(冰冻集合)

不可以修改的集合

list、tuple、set转换问题

  • list、tuple、set之间的转换,转换的内容必须是可迭代的
  • list、tuple转换成set时,set会对数字进行从小到大的排序
# list、tuple、set转换问题案例
a = 100
b = [100]
c = (5, 23, 4, 6, 9, 0, 23)

t1 = tuple(a)
print(type(t1))
print(t1)

t2 = tuple(b)
print(type(t2))
print(t2)

s1 = set(a)
print(type(s1))
print(s1)

s2 = set(b)
print(type(s2))
print(s2)

s3 = set(c)
print(type(s3))
print(s3)

"""
TypeError: 'int' object is not iterable

(100,)
TypeError: 'int' object is not iterable

{100}

{0, 4, 5, 6, 9, 23}
"""

字典(dict)

一种键值对形式的组合数据

  • 字典是序列类型,无序,所以没有切片和索引操作
  • 字典中的每个数据都由键值对组成,即kv对
    • key:必须是可哈希的,比如int,string,float,tuple
    • value:任何值
#  dict案例
d1 = {}
d2 = {1: '1', '2': 2, (1, 2, 3): [1, 2, 3], 1.1: {1: {1, 2, 3}}}

print(type(d1))
print(d1)
print(type(d2))
print(d2)

"""
运行结果:

{}

{1: '1', '2': 2, (1, 2, 3): [1, 2, 3], 1.1: {1: {1, 2, 3}}}
"""

字典的常见操作

# 访问修改删除数据操作案例
d = {'one': 1, 'two': 2, 3: 'three'}

print(d['one'])

# 修改数据
d['one'] = 'Hello'
print(d)

# 删除数据
del d['one']
print(d)

"""
运行结果:
1
{'one': 'Hello', 'two': 2, 3: 'three'}
{'two': 2, 3: 'three'}
"""
# 成员检测案例
# 成员检测时,检测的是key的内容
d = {'one': 1, 'two': 2, 'three': 3}
if 2 in d:
    print('value')
if 'two' in d:
    print('key')
if ('two', 2) in d:
    print('key and value')
    
"""
运行结果:
key
"""
# dict的循环访问案例
d = {'one': 1, 'two': 2, 'three': 3}
for k in d:
    print(k, '--', d[k])
    
print('*' * 20)

for k in d.keys():
    print(k)
    
for v in d.values():
    print(v)
    
for k,v in d.items():
    print(k, '--', v)
    
"""
运行结果:
one -- 1
two -- 2
three -- 3
********************
one
two
three
1
2
3
one -- 1
two -- 2
three -- 3
"""
# 字典的生成式案例
d1 = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
d2 = {k: v for k, v in d1.items() if v % 2 == 0}
d3 = {k: 'None' for k in range(0, 5)}

print(d2)
print(d3)

"""
运行结果:
{'two': 2, 'four': 4}
{0: 'None', 1: 'None', 2: 'None', 3: 'None', 4: 'None'}
"""
# 字典变成其他类型案例
d = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
st = str(d)
l = list(d)
t = tuple(d)
se = set(d)

print(type(st))
print(st)
print(type(l))
print(l)
print(type(t))
print(t)
print(type(se))
print(se)

"""
运行结果:

{'one': 1, 'two': 2, 'three': 3, 'four': 4}

['one', 'two', 'three', 'four']

('one', 'two', 'three', 'four')

{'two', 'four', 'one', 'three'}
"""

字典常用函数

items()

获取字典的键值对

  • 格式:dict.items()
  • 返回值:字典的键值对组成的元组结构
# items()案例
d = {'one': 1, 'two': 2, 'three': 3}
i = d.items()
print(type(d))
print(d)
print(type(i))
print(i)

"""
运行结果:

{'one': 1, 'two': 2, 'three': 3}

dict_items([('one', 1), ('two', 2), ('three', 3)])
"""

keys()

获取字典的键

  • 格式:dict.keys()
  • 返回值:字典的键组成的元组结构
# keys()案例
d = {'one': 1, 'two': 2, 'three': 3}
k = d.keys()

print(type(k))
print(k)

"""
运行结果:

dict_keys(['one', 'two', 'three'])
"""

values()

获取字典的值

  • 格式:dict.values()
  • 返回值:字典的值组成的元组结构
# values()案例
d = {'one': 1, 'two': 2, 'three': 3}
v = d.values()

print(type(v))
print(v)

"""
运行结果:

dict_values([1, 2, 3])
"""

get()

根据指定的键返回相应的值,和普通方法相比,get()可以设置默认值

  • 格式:dict.get(key, default_value)
  • 返回值:字典的值或设置的默认值
# get()案例
d = {'one': 1, 'two': 2, 'three': 3}
print(d.get("four"))

# get的默认值是None,可以设置
print(d.get("one", 100))
print(d.get("four", 100))

print(d["four"])

"""
运行结果:
None
1
100
KeyError: 'four'
"""

fromkeys()

使用指定的序列作为键,使用一个值作为所有键的值

  • 格式:dict.fromkeys(sequence, value)
  • 返回值:生成一个字典
# fromkeys()案例
l = ['Guitar', 'Write', 'Code']
d = dict.fromkeys(l, 'Good')

print(type(d))
print(d)

"""
运行结果:

{'Guitar': 'Good', 'Write': 'Good', 'Code': 'Good'}
"""

可迭代对象常用函数

len()

获取长度

  • 格式:len(str/list/tuple/set/dict...)
  • 返回值:int类型的数字(表示长度)
# len()案例
st = 'I am madman'
l = [1, 2, 3, 4, 5, (1, 2, 3, 4, 5)]
t = (1, 2, 3, 4, 5, {1, 2, 3, 4, 5})
se = {1, 2, 3, 4, 5, (1, 2, 3, 4, 5)}
d = {'name': 'Madman', 'age': 23, 'local': 'Shenzhen'}

print(type(len(st)))
print(len(st))
print(type(len(l)))
print(len(l))
print(type(len(t)))
print(len(t))
print(type(len(se)))
print(len(se))
print(type(len(d)))
print(len(d))

"""
运行结果:

11

6

6

6

3
"""

min()/max()

求最小值/最大值

  • 格式:min/max(str/list/tuple/set/dict...)
  • 返回值:最小值/最大值的内容,一般是int或str
  • 注意:不同类型的数据使用min()/max()会报错,因为函数本质上是数据的对比
# min()/max()案例
l1 = [77, 44, 99, 1, 34]
l2 = ['a', 'ab', 'A', 'AB']
l3 = [1, 2, 'Madman']
l4 = [1, 2, (1, 2, 3)]

st = 'I am madman'
t = ('I', 'am', 'madman', 'me')
se = {1, 2, 3, 4, 5, 77, 88}
d = {'name': 'Madman', 'age': 23, 'local': 'Shenzhen'}

print(type(max(l1)))
print(max(l1))
print(type(max(l2)))
print(max(l2))
print(type(max(l3)))
print(max(l3))
print(type(max(l4)))
print(max(l4))

print(type(max(st)))
print(max(st))
print(type(max(t)))
print(max(t))
print(type(max(se)))
print(max(se))
print(type(max(d)))
print(max(d))

"""
运行结果:

99

ab
TypeError: '>' not supported between instances of 'str' and 'int'
TypeError: '>' not supported between instances of 'tuple' and 'int'

n

me

88

name
"""

count()

对某一元素进行计数

  • 格式:str/list/tuple.count(value)
  • 返回值:int类型的数字(表示数目)
  • 注意:set和dict无法使用
# count()案例
st = 'I am madman'
l = [1, 2, 3, 4, 5, (1, 2, 3, 4, 5), 1, 2, 2]
t = (1, 2, 3, 4, 5, {1, 2, 3, 4, 5}, 1, 2, 2)
se = {1, 2, 3, 4, 5, (1, 2, 3, 4, 5), 1, 2, 2}
d = {'name': 'Madman', 'age': 23, 'local': 'Shenzhen'}

print(type(st.count('m')))
print(st.count('m'))
print(type(l.count(2)))
print(l.count(2))
print(type(t.count(2)))
print(t.count(2))
print(type(se.count(2)))
print(se.count(2))
print(type(d.count('name')))
print(d.count('name'))

"""
返回结果:

3

3

3
AttributeError: 'set' object has no attribute 'count'
AttributeError: 'dict' object has no attribute 'count'
"""

index()

某一元素从左往右第一次出现的位置

  • 格式:obj.index(value)
  • 返回值:int类型的数字(表示位置)
  • 注意:set和dict无法使用
# index()案例
st = 'I am madman'
l = [1, 2, 3, 4, 5, (1, 2, 3, 4, 5), 1, 2, 2]
t = (1, 2, 3, 4, 5, {1, 2, 3, 4, 5}, 1, 2, 2)
se = {1, 2, 3, 4, 5, (1, 2, 3, 4, 5), 1, 2, 2}
d = {'name': 'Madman', 'age': 23, 'local': 'Shenzhen'}

print(type(st.index('ma')))
print(st.index('ma'))
print(type(l.index(2)))
print(l.index(2))
print(type(t.index({1, 2, 3, 4, 5})))
print(t.index({1, 2, 3, 4, 5}))
print(type(se.index((1, 2, 3, 4, 5))))
print(se.index((1, 2, 3, 4, 5)))
print(type(d.index('age')))
print(d.index('age'))

"""
运行结果:

5

1

5
AttributeError: 'set' object has no attribute 'index'
AttributeError: 'dict' object has no attribute 'index'
"""

add()

添加指定元素

  • 格式:set.add(element)
  • 返回值:None
  • 注意:只能用在set上
# add()案例
st = 'I am madman'
l = [1, 2, 3, 4, 5]
t = (1, 2, 3, 4, 5)
se = {1, 2, 3, 4, 5}

print(st.add('!'))
print(st)
print(l.add(6))
print(l)
print(t.add(6))
print(t)
print(se.add(6))
print(se)
print(se.add((7, 8, 9)))
print(se)

"""
运行结果:
AttributeError: 'str' object has no attribute 'add'
AttributeError: 'list' object has no attribute 'add'
AttributeError: 'tuple' object has no attribute 'add'
None
{1, 2, 3, 4, 5, 6}
None
{1, 2, 3, 4, 5, 6, (7, 8, 9)}
"""

remove()

删除指定元素(会报错)

  • 格式:list/set.remove(element)
  • 返回值:None
  • 注意
    • 只能用在list、set上
    • 如果删除不存在的元素,会报错
# remove()案例
st = 'I am madman'
l = [1, 2, 3, 1]
t = (1, 2, 3, 1)
se = {1, 2, 3, 4, (1, 2, 3)}

print(st.remove('I'))
print(st)
print('*' * 20)

print(l.remove(1))
print(l)
print(l.remove(1))
print(l)
print(l.remove(1))
print(l)
print('*' * 20)

print(t.remove(1))
print(t)
print(t.remove(1))
print(t)
print(t.remove(1))
print(t)
print('*' * 20)

print(se.remove(4)
print(se)
print(se.remove((1, 2, 3)))
print(se)
print(se.remove(4))
print(se)

"""
运行结果:
AttributeError: 'str' object has no attribute 'remove'
********************
None
[2, 3, 1]
None
[2, 3]
ValueError: list.remove(x): x not in list
********************
AttributeError: 'tuple' object has no attribute 'remove'
********************
None
{1, 2, 3, (1, 2, 3)}
None
{1, 2, 3}
"""

discard()

删除指定元素(不报错)

  • 格式:set.discard(elemnet)
  • 返回值:None
  • 注意
    • 只能用到set上
    • 如果删除不存在的元素,不报错
# discard()案例
st = 'I am madman'
l = [1, 2, 3, 1]
t = (1, 2, 3, 1)
se = {1, 2, 3, 4, (1, 2, 3)}

print(st.remove('I'))
print(st)
print('*' * 20)

print(l.discard(1))
print(l)
print('*' * 20)

print(t.discard(1))
print(t)
print('*' * 20)

print(se.discard(4))
print(se)
print(se.discard((1, 2, 3)))
print(se)
print(se.discard(4))
print(se) 

"""
运行结果:
AttributeError: 'str' object has no attribute 'remove'
********************
AttributeError: 'list' object has no attribute 'discard'
********************
AttributeError: 'tuple' object has no attribute 'discard'
********************
None
{1, 2, 3, (1, 2, 3)}
None
{1, 2, 3}
None
{1, 2, 3}
"""

pop()

弹出一个元素

  • 格式
    • list:list.pop(index=-1)
    • set:set.pop()
    • dict:dict.pop(key)
  • 返回值:弹出的元素
  • 注意
    • 只能用在list、set、dict上
    • 如果list、set、dict为空,报错
    • list默认弹出最后的元素,可以用索引指定弹出的元素
    • set默认弹出最前的元素
    • dict使用pop()时一定要指定key
# pop()案例
st = 'I am madman'
l = [1, 2, 3, 1, {1, 2, 3}]
t = (1, 2, 3, 1)
se = {1, 2, 3, 4, (1, 2, 3)}
d = {'name': 'madman', 'age': 23, 'local': 'Shenzhen'}

print(st.pop())
print(st)
print('*' * 20)

print(l.pop(2))
print(l)
print(l.pop())
print(l)
print('*' * 20)

print(t.pop())
print(t)
print('*' * 20)

print(se.pop())
print(se)
print(se.pop())
print(se)
print('*' * 20)

print(d.pop('name'))
print(d)
print(d.pop())
print(d)

"""
运行结果:
AttributeError: 'str' object has no attribute 'pop'
********************
3
[1, 2, 1, {1, 2, 3}]
{1, 2, 3}
[1, 2, 1]
********************
AttributeError: 'tuple' object has no attribute 'pop'
********************
1
{2, 3, 4, (1, 2, 3)}
2
{3, 4, (1, 2, 3)}
********************
madman
{'age': 23, 'local': 'Shenzhen'}
TypeError: pop expected at least 1 arguments, got 0
"""

你可能感兴趣的:(Python)