day07-列表类型/元组类型/字典类型/集合类型内置方法

列表类型内置方法

用来存多个元素,[]内用逗号隔开任意数据类型的元素

1. list()强制类型转换

print(list('name'))
['n', 'a', 'm', 'e']

2. 按索引取值:正向取值+反向取值,既可以存也可以取

hobby = ['run', 'read', 'fishing', 'singing','rap','travelling']
print(hobby[1])    # 取第二个元素
print(hobby[-1])    # 取最后一个元素
hobby[0] = 'swimming'    # 改变列表中的元素 
print(hobby)
read
travelling
['swimming', 'read', 'fishing', 'singing', 'rap', 'travelling']

3. 切片:正向切片+反向切片

hobby = ['run', 'read', 'fishing', 'singing','rap','travelling']
print(hobby[:3])    # 取前三个元素
print(hobby[-1:-4:-1])    # 取后三个值
['run', 'read', 'fishing']
['travelling', 'rap', 'singing']

4. 长度len:获取列表的长度

hobby = ['run', 'read', 'fishing', ['singing','rap','travelling']]
print(len(hobby))
4

5. 成员运算 in|not in:判断元素是否在列表内,返回布尔值True或者False

hobby = ['run', 'read', 'fishing', ['singing','rap','travelling']]
print('run' in hobby)
print('rap' in hobby)    # 'rap'是hobby中某个元素的其中一个元素,不是hobby的元素,所以返回False
True
False

6.追加append(self, p_object):在列表的最后加入一个数据

hobby = ['run', 'read', 'fishing', ['singing','rap','travelling']]
hobby.append('hiking')    # 在列表的最后添加
print(hobby)
['run', 'read', 'fishing', ['singing', 'rap', 'travelling'], 'hiking']

7. 删除del:删除列表

hobby = ['run', 'read', 'fishing', ['singing','rap','travelling']]
del hobby

8. 循环:将列表中的元素一个个取出来

hobby = ['run', 'read', 'fishing', ['singing','rap','travelling']]
for i in hobby:
    print(i)
run
read
fishing
['singing', 'rap', 'travelling']

9. 插入元素insert(self, index, p_object):index是索引值,p_object是要插入的对象。在指定索引前插入一个值

hobby = ['run', 'read', 'fishing', ['singing','rap','travelling']]
hobby.insert(-1,'swimming')    # 在指定位置-1的前面插入一个值
print(hobby)
['run', 'read', 'fishing', 'swimming', ['singing', 'rap', 'travelling']]

10.删除元素pop(self, index=None):删除指定索引的值,不写默认删除最后一个值。返回被删除的值

hobby = ['run', 'read', 'fishing', ['singing','rap','travelling']]
print(hobby.pop())    # 删除最后一个值
print(hobby.pop(0))    # 删除第一个值
print(hobby)
['singing', 'rap', 'travelling']
run
['read', 'fishing']

11. 移除remove(self, value):按指定元素删除对象,不存在时则报错

hobby = ['run', 'read', 'fishing', ['singing','rap','travelling']]
hobby.remove('run')
print(hobby)
hobby.remove('rap')    # 报错:‘rap不在列表里’
['read', 'fishing', ['singing', 'rap', 'travelling']]
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-21-61db1bc842bd> in <module>
      2 hobby.remove('run')
      3 print(hobby)
----> 4 hobby.remove('rap')    # 报错:‘rap不在列表里’
ValueError: list.remove(x): x not in list

12.计数count(self, value):获取指定元素在列表中出现的次数

hobby = ['run', 'read', 'run', ['singing','rap','travelling']]
print(hobby.count('run'))
2

13. 索引index(self, value, start=None, stop=None):获取指定元素的索引

hobby = ['run', 'read', 'run', ['singing','rap','travelling']]
print(hobby.index('read'))
1

14. 清空列表clear:清空列表里的元素,得到一个空列表

hobby = ['run', 'read', 'run', ['singing','rap','travelling']]
hobby.clear()
print(hobby)
[]

15. 复制copy:复制列表,不改变原列表

hobby = ['run', 'read', 'run', ['singing','rap','travelling']]
new_list = hobby.copy()
print(new_list)
print(hobby)
['run', 'read', 'run', ['singing', 'rap', 'travelling']]
['run', 'read', 'run', ['singing', 'rap', 'travelling']]

16.扩展extend(self, iterable):iterable是可迭代对象,可以放列表,字符串

hobby = ['run', 'read', 'run', ['singing','rap','travelling']]
hobby.extend(['hiking','fishing'])    # 将元素加到列表的后面
print(hobby)
['run', 'read', 'run', ['singing', 'rap', 'travelling'], 'hiking', 'fishing']

17. 反转reverse:将列表反转

hobby = ['run', 'read', 'run', ['singing','rap','travelling']]
hobby.reverse()
print(hobby)
[['singing', 'rap', 'travelling'], 'run', 'read', 'run']

18. 排序sort(self, key=None, reverse=False):reverse为False时是默认按从小到大排序,不为False时是从大到小排序

hobby = ['run', 'read', 'fishing']
hobby.sort()    # 默认从小到大排序
print(hobby)
hobby.sort(reverse=1)    # 不为False时,从大到小排序 
print(hobby)
['fishing', 'read', 'run']
['run', 'read', 'fishing']

注意:列表中必须是同类型元素,才能进行排序,否则会报错

hobby = ['run', 'read', 'run', 1]
hobby.sort()   
print(hobby)
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-46-10793fa985bf> in <module>
      1 hobby = ['run', 'read', 'run', 1]
----> 2 hobby.sort()
      3 print(hobby)
TypeError: '<' not supported between instances of 'int' and 'str'

元组类型内置方法

类似于列表,只不过元组只能取不能更改。在()内用逗号隔开任意数据类型的元素

1. 索引取值

tuple = ('a','b','c','b')
print(tuple[0])    # 打印元组的第一个元素
a

2. 切片

tuple = ('a','b','c','b')
print(tuple[0:3])    # 打印元组前三个元素
('a', 'b', 'c')

3. 长度len:获取元组的长度

tuple = ('a','b','c','b')
print(len(tuple))
4

4. 成员运算符 in|not in:判断数据是不是在元组内

tuple = ('a','b','c','b')
print('c' in tuple)
True

5. 循环:取元组的值

tuple = ('a','b','c','b')
for i in tuple:
    print(i)

6. 计数count:获取指定元素在元组中的个数

tuple = ('a','b','c','b')
print(tuple.count('b'))
2

7. 索引值index:获取指定元素的索引值,当元素不存在时报错

tuple = ('a','b','c','b')
print(tuple.index('c'))    # 返回元素的索引
print(tuple.index('d'))    # 不存在时报错
2
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-3-84596206fce9> in <module>
      1 tuple = ('a','b','c','b')
      2 print(tuple.index('c'))
----> 3 print(tuple.index('d'))
ValueError: tuple.index(x): x not in tuple

字典类型内置方法

当列表存很多值的时候,列表会显得很乱,所以有了字典。在{}内以逗号分隔开多个键值对key:value的值,key一般为字符串,因为key一般具有描述意义

1. 按键存取值,可存可取

info_dict = {'name':'nick','age':18,'height':'180cm','hobby':['read','run','fishing']}
print(info_dict['name'])    # 通过key取值
info_dict['weight'] = 140    # 通过key存值
print(info_dict)
nick
{'name': 'nick', 'age': 18, 'height': '180cm', 'hobby': ['read', 'run', 'fishing'], 'weight': 140}

2. 长度len:获取字典的长度

info_dict = {'name':'nick','age':18,'height':'180cm','hobby':['read','run','fishing']}
print(len(info_dict))    
4

3. 成员运算符 in|not in:判断字符是否在字典的key中,判断的是key值

info_dict = {'name':'nick','age':18,'height':'180cm','hobby':['read','run','fishing']}
print('name' in info_dict)    # 'name'在字典的key
print('nick' in info_dict)    # 'nick'不在字典中
True
False

4. 删除del:删除字典

info_dict = {'name':'nick','age':18,'height':'180cm','hobby':['read','run','fishing']}
del info_dict

5. 取键keys:获取字典的键;取值values:获取字典的值;取键值对items:获取字典的键值对

info_dict = {'name':'nick','age':18,'height':'180cm','hobby':['read','run','fishing']}
print(info_dict.keys())
print(info_dict.values())
print(info_dict.items())
dict_keys(['name', 'age', 'height', 'hobby'])
dict_values(['nick', 18, '180cm', ['read', 'run', 'fishing']])
dict_items([('name', 'nick'), ('age', 18), ('height', '180cm'), ('hobby', ['read', 'run', 'fishing'])])

6. 循环:

info_dict = {'name':'nick','age':18,'height':'180cm','hobby':['read','run','fishing']}
for key in info_dict.keys():
    print(key)
for value in info_dict.values():
    print(value)
for k,v in info_dict.items():
    print(k,v)
name
age
height
hobby
nick
18
180cm
['read', 'run', 'fishing']
name nick
age 18
height 180cm
hobby ['read', 'run', 'fishing']

7. get(self, k, d=None):获取指定键的值,如果key不存在,返回None,也可以指定返回值,不会报错。

info_dict = {'name':'nick','age':18,'height':'180cm','hobby':['read','run','fishing']}
print(info_dict.get('name'))    # 获取'name'的值
print(info_dict.get('weight','140'))    # 当指定的key不存在时,返回指定的值
nick
140

8. update(self, E=None, F):有就更新,没有就添加**

info_dict = {'name':'nick','age':18,'height':'180cm','hobby':['read','run','fishing']}
new = {'name':'Jim','weight':'140'}
info_dict.update(new)    # 当new里的键在info_dict中,有new所对应的值替换info_dict的值;键不存在时就添加到info_dict中去
print(info_dict)
{'name': 'Jim', 'age': 18, 'height': '180cm', 'hobby': ['read', 'run', 'fishing'], 'weight': '140'}

9. fromkeys:默认把给定的列表内的元素取出来当成key,然后使用一个默认的value新建一个字典

dic = dict.fromkeys([1,2,3],None)    # 将列表中的元素当key,第二个元素当value,新建一个字典
print(dic)
{1: None, 2: None, 3: None}

10. setdefault(self, k, d=None):如果字典中有该key的话,则key对应的值不变,没有则增加d

info_dict = {'name':'nick','age':18,'height':'180cm','hobby':['read','run','fishing']}
print(info_dict.setdefault('name'))    # 'name'在info_dict中,返回'name'的值
print(info_dict.setdefault('weight','140'))    # 'weight'不在info_dict中,返回指定值,同时将该键值对增加到字典中
print(info_dict)
nick
140
{'name': 'nick', 'age': 18, 'height': '180cm', 'hobby': ['read', 'run', 'fishing'], 'weight': '140'}

11. 清除clear():清空字典

info_dict = {'name':'nick','age':18,'height':'180cm','hobby':['read','run','fishing']}
info_dict.clear()
print(info_dict)
{}

12. copy复制:不改变原字典

info_dict = {'name':'nick','age':18,'height':'180cm','hobby':['read','run','fishing']}
print(info_dict.copy())
print(info_dict)
{'name': 'nick', 'age': 18, 'height': '180cm', 'hobby': ['read', 'run', 'fishing']}
{'name': 'nick', 'age': 18, 'height': '180cm', 'hobby': ['read', 'run', 'fishing']}

13. pop(self, k, d=None):删除指定的键并返回相应的值。如果没有找到key,则返回d,否则将引发KeyError

info_dict = {'name':'nick','age':18,'height':'180cm','hobby':['read','run','fishing']}
print(info_dict.pop('hobby'))
print(info_dict.pop('weight',None))
['read', 'run', 'fishing']
None

14. popitem(self):删除并返回(key, value)对作元组;但如果D为空,则引发KeyError

info_dict = {'name':'nick','age':18,'height':'180cm'}
print(info_dict.popitem())    # 删除了键值对‘height’:'180cm',并将其作为元组返回
print(info_dict)
('height', '180cm')
{'name': 'nick', 'age': 18}

集合类型内置方法

集合用来存储多个值,在{}内以逗号分隔开多个元素,这个元素必须是不可变类型。
注意:用set()来定义一个空集合

1. 去重:在去重的同时,打乱了列表元素原有的顺序

l = [7,1,2,1,3,2,4,5,1]
print(set(l))
{1, 2, 3, 4, 5, 7}

2. 长度len:获取集合的长度

set = {'a','f','h','e'}
print(len(set))
4

3.成员运算 in|not in:判断字符是否在集合内

set = {'a','f','h','e'}
print('f' in set)
True

4.并集union 或符号“|”

set1 = {'a','f','h','e'}
set2 = {'a','g','i','e'}
print(set1.union(set2))    #在set1中或者在set2中的字符集合
print(set1|set2)
{'e', 'h', 'a', 'g', 'f', 'i'}
{'e', 'h', 'a', 'g', 'f', 'i'}

5.交集intersection 或符号“&”

set1 = {'a','f','h','e'}
set2 = {'a','g','i','e'}
print(set1.intersection(set2))    # 在set1中又在set2中的字符集合
print(set1&set2)
{'e', 'a'}
{'e', 'a'}

5.差集difference 或符号“-”

set1 = {'a','f','h','e'}
set2 = {'a','g','i','e'}
print(set1.difference(set2))    # 在set1中、不在set2中的字符集合
print(set1-set2)
{'h', 'f'}
{'h', 'f'}

6.对称差集symmetric_difference 或符号“^”

set1 = {'a','f','h','e'}
set2 = {'a','g','i','e'}
print(set1.symmetric_difference(set2))    # 就是并集减去交集,不同时在set1、set2的字符集合
print(set1^set2)
{'h', 'g', 'f', 'i'}
{'h', 'g', 'f', 'i'}

7.父集issuperset 或符号">/>="

set1 = {'a','f','h','e'}
set2 = {'a','e'}
print(set1.issuperset(set2))    # 就是set1是否包含set2中所有的字符
print(set1>set2)
print(set1>=set2)
True
True

8.子集issubset 或符号"</<="

set1 = {'a','e'}
set2 = {'a','f','h','e'}
print(set1.issubset(set2))    # 就是set1中所有的字符是否全在set2中
print(set1 < set2)
print(set1 <= set2)
True
True
True

9.是否相等"=="

set1 = {'a','e'}
set2 = {'a','e'}
print(set1 == set2)    # 两集合是否相等
True

10.添加元素add

set = {'a','e'}
set.add('f')
print(set)
{'e', 'f', 'a'}

11.移除元素remove:元素不存时则报错

set = {'a','e'}
set.remove('a')
print(set)
{'e'}

12.difference_update:删除另一集合中有的元素

set1 = {'a','e'}
set2 = {'a','f','h','e'}
set2.difference_update(set1)    # 删除set2中在set1中存在的元素
print(set2)
{'h', 'f'}

13.discard:删除元素,元素不存在时不报错

set1 = {'a','e'}
set1.discard('a')
print(set1)
{'e'}

14.isdisjoint:判断两交集是否为空,为空返回True,不为空返回False

set1 = {'a','e'}
set2 = {'f','h'}
print(set1.isdisjoint(set2))
True
上一篇:python3 day07 练习题


下一篇:day07 分支,循环