栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python中list基础与dict拓展

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python中list基础与dict拓展

一. list列表扩展的方式有3种

后缀扩展

list.后输入append

2.插入数值

list.insert

3.合并列表

list.extend

 2. 对["cherry", "litchi", "strawberry", "mangosteen", "pomelo", "pineapple", "pitaya", "durian"]进行默认排序

fruit_list = ["cherry", "litchi", "strawberry", "mangosteen", "pomelo", "pineapple", "pitaya", "durian"]
fruit_list.sort()
print(fruit_list)

 按照第三个字母排序

def sort_func(x):
    return (x[3])
fruit_list = ["cherry", "litchi", "strawberry", "mangosteen", "pomelo", "pineapple", "pitaya", "durian"]
fruit_list.sort(key=sort_func)
print(fruit_list)

三. dict中所有方法的使用 

1.pop移除序列中一个指定元素,并返回该元素的值

dict_y = {int: 1, bytes: 2+2j}
dict_y.pop(int)
print(dict_y)

 2.clear清除全部元素。

dict_y = {int: 1, bytes: 2+2j}
dict_y.clear()
print(dict_y)

 

 3.copy分为深浅靠背

dict_y = {int: 1, bytes: 2+2j, float: 1.1}
dict_2y = dict_y
dict_3y = dict_y.copy()
dict_y['int: 1'] = 'int: 3'
print(dict_y)
print(dict_2y)
print(dict_3y)

 

dict3为深拷贝不会因为父目录的变化而变化,dict2为dict1的 引名会随着父目录改变

4.fromkeys:创造一个新的字典并返回

dict_y = dict.fromkeys([1, 2, 3], 'hello')
print(dict_y)

 

 

dict_y = dict.fromkeys([1, 2, 3], ['hello', 'hi'])
print(dict_y)

 

 5.get返回指定的赋值如果没有为缺省值

dict_y = {int: 1, bytes: 2+2j }
print(dict_y.get(int))

 

 6.items以列表形式返回可遍历元素组

dict_y = {int: 1, bytes: 2+2j }
print(dict_y.items())

 

 7.keys返回一个可迭代xulie

dict_y = {int: 1, bytes: 2+2j}
print(dict_y.keys())

 

8. popitem删除元素只留列表最后一个元素

dict_y = {int: 1, bytes: 2+2j, float: 1.1}
print(dict_y.popitem())

 

 

dict_y = {int: 1, bytes: 2+2j}
print(dict_y.popitem())

 

 9,setdefault接受一个值或者缺省值并返回该值

dict_y = {int: 1, bytes: 2+2j, float: 1.1}
print(dict_y.setdefault('com', 2+2j))

 

10.update使用可使原字典所含元素更新

dict_y = {int: 1, bytes: 2+2j, float: 1.1}
dict_2y = {float: 2.2}
dict_y.update(dict_2y)
print(dict_y)

 

 11.values返回字典中所包含的值

 

dict_y = {int: 1, bytes: 2+2j, float: 1.1}
print(dict_y.values())

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/953636.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号