开启变身模式

大家好, 从这一期开始,我们会从小白变身为中等小白,在基础起步阶段有太多的东西我没有讲到,但是俗话说的好,无他,但手熟尔,只要多多练习,时间会是最好的证明,相信我们终有一天会成为高手,因此从这一系列开始,让我们一起更上一层楼,还是和往常一样,我也是水平不高,如果有大神发现文章中的错误一定要指出哈~

先皮一下,看个欧阳修的<<卖油翁>>:

陈康肃公尧咨善射,当世无双,公亦以此自矜。尝射于家圃,有卖油翁释担而立,睨之,久而不去。见其发矢十中八九,但微颔之。

康肃问曰:“汝亦知射乎?吾射不亦精乎?”翁曰:“无他,但手熟尔。”康肃忿然曰:“尔安敢轻吾射!”翁曰:“以我酌油知之。”乃取一葫芦置于地,以钱覆其口,徐以杓酌油沥之,自钱孔入,而钱不湿。因曰:“我亦无他,惟手熟尔。”康肃笑而遣之。

List的进阶用法

这里我将会详细介绍一些我认为非常不错的List的使用方法,至于list 自带的一些基础用法,这里不再说明,感兴趣的朋友们可以看看我的基础教程: Python 基础起步 (五) 一定要知道的数据类型:初识List 和 Python 基础起步 (六) List的实用技巧大全, 好啦,闲话少说,让我们开始吧

把其他类型数据结构转化为List类型

利用list(target)即可实现把其他类型的数据结构转化为List类型,十分实用,我们可以把字符串,元组等数据结构转化为List,也可以直接创建,像下图一样:


print(list())                            # 创建空ListvowelString = 'aeiou'                    # 把字符串转化为List
print(list(vowelString))vowelTuple = ('a', 'e', 'i', 'o', 'u')  # 从元组tuple转化为List
print(list(vowelTuple))vowelList = ['a', 'e', 'i', 'o', 'u']   # 从List到List
print(list(vowelList))vowelSet = {'a', 'e', 'i', 'o', 'u'}    #  从Set到List
print(list(vowelSet))Out: []['a', 'e', 'i', 'o', 'u']['a', 'e', 'i', 'o', 'u']['a', 'e', 'i', 'o', 'u']['a', 'e', 'i', 'o', 'u']

可能平时用的比较多的一般是从一个dict中提取 keys 和 values :

person = {'name':'Peppa Pig','age':15,'country':'bratian'}person_keys = list(person.keys())
person_values = list(person.values())print(list(person))  # 如果直接转化一个字典只会把keys提取出来
print(list(person.keys()))
print(list(person.values()))Out:['name', 'age', 'country']    ['name', 'age', 'country']             # 把字典中的Keys提出['Peppa Pig', 15, 'bratian']           # 把字典中的Values提出

这里大家稍微注意下,如果直接用list(person)会默认等同于person.keys()

List排序方法汇总

总体来说,有两种方法最为便捷,List.sort 或者 sorted(List),具体来看如何实现,先看升序:

vowels = ['e', 'a', 'u', 'o', 'i']
vowels.sort()
print('Sorted list Acending:', vowels)  # 使用sort
Out: Sorted list Acending: ['a', 'e', 'i', 'o', 'u']
vowels = ['e', 'a', 'u', 'o', 'i']
print('Sorted list Acending:', sorted(vowels))  # 使用sorted
Out:Sorted list Acending: ['a', 'e', 'i', 'o', 'u']

再来看降序:

vowels = ['e', 'a', 'u', 'o', 'i']
vowels.sort(reverse=True)     # 使用sort
print('Sorted list (in Descending):', vowels)
Out: Sorted list (in Descending): ['u', 'o', 'i', 'e', 'a']
vowels = ['e', 'a', 'u', 'o', 'i']
print('Sorted list (in Descending):', sorted(vowels,reverse=True))  # 使用sorted方法
Out:Sorted list (in Descending): ['u', 'o', 'i', 'e', 'a']

其实这里里面还有一个关键的参数是key,我们可以自定义一些规则排序,下面看个例子,用的是默认的len函数
,让我们根据List中每个元素的长度来排序,首先是升序:

vowels = ['I', 'live', 'at', 'Paris', 'I','love','Python']
# 使用sort
vowels.sort(key=len)
print('Sorted by lenth Ascending:', vowels)
Out:Sorted by lenth: ['I', 'I', 'at', 'live', 'love', 'Paris', 'Python']
vowels = ['I', 'live', 'at', 'Paris', 'I','love','Python']
# 使用 sorted
print('Sorted by lenth Ascending:', sorted(vowels,key=len))
Out:Sorted by lenth Ascending: ['I', 'I', 'at', 'live', 'love', 'Paris', 'Python']

降序也差不多啦:

vowels = ['I', 'live', 'at', 'Paris', 'I','love','Python']
vowels.sort(key=len,reverse=True)
print('Sorted by lenth Descending:', vowels)
Out:Sorted by lenth Descending: ['Python', 'Paris', 'live', 'love', 'at', 'I', 'I']
vowels = ['I', 'live', 'at', 'Paris', 'I','love','Python']
print('Sorted by lenth Descending:', sorted(vowels,reverse=True))
Out:Sorted by lenth Descending: ['Python', 'Paris', 'live', 'love', 'at', 'I', 'I']

有关这个key我们可以自己定义,请看下面的大栗子:

def takeSecond(elem):return elem[1]random = [(2, 2), (3, 4), (4, 1), (1, 3)]
random.sort(key=takeSecond) # sort list with key
print('Sorted list:', random)Out: [(4, 1), (2, 2), (1, 3), (3, 4)]

这里因为列表中的元素都是元组,所以我们规定按照元组的第二个数排序,所以结果如上,默认依然是reverse=False ,也就是升序,至于其他有意思的方法大家可以自己开发

逆序输出List

如果我们想要逆序输出一个List,简单来说有两种方法比较好用,切片和reverse,来看例子:

    vowels = ['I', 'live', 'at', 'Paris', 'I','love','Python']print(list(reversed(vowels)))print(list[::-1])
Out:['Python', 'love', 'I', 'Paris', 'at', 'live', 'I']   ['Python', 'love', 'I', 'Paris', 'at', 'live', 'I']   

利用Range生成List

Python里面为我们提供了一个超好用的方法range(),具体的用法很多,不在这里一一讲解啦,但是大家可以看一下它如何和List结合在一起的:

five_numbers=list(range(5))  #创建0~4的List
print(five_numbers)odd_numbers=list(range(1,50,2))   #创建0~50所有的奇数的List
print(odd_numbers)even_numbers=list(range(0,50,2))  #创建0~50所有的偶数的List
print(even_numbers)

其实很简单,用的最多的就是range(start, stop, hop)这个结构,其他的大家可以自行查询哈

List列表推导式

其实这个东西无非就是为了减少代码书写量,比较Pythonic的东西,基础模板如下:

variable = [out_exp for out_exp in input_list if out_exp == 2]

大家直接看比较麻烦,还是直接上代码吧:

S = [x**2 for x in range(8)]      # 0~7每个数的平方存为List
V = [2**i for i in range(8)]      # 2的 0~7次方
M = [x for x in S if x % 2 == 0]  #找出在S里面的偶数print(S)
print(V)
print(M)Out:   Square of 0 ~7:  [0, 1, 4, 9, 16, 25, 36, 49]The x power of 2,(0<x<7) :  [1, 2, 4, 8, 16, 32, 64, 128]The even numbers in S:  [0, 4, 16, 36]

通过这个小栗子大家估计已经明白用法啦,推导式还可以这么用:

verbs=['work','eat','sleep','sit']
verbs_with_ing=[v+'ing' for v in verbs]   # 使一组动词成为现在分词
print(verbs_with_ing)Out:['working', 'eating', 'sleeping', 'siting']

或者加上查询条件if :

all_numbers=list(range(-7,9))
numbers_positive = [n for n in all_numbers if n>0 ]
numbers_negative = [n for n in all_numbers if n<0]
devided_by_two = [n for n in all_numbers if n%2==0]print("The positive numbers between -7 to 9 are :",numbers_positive)
print("The negative numbers between -7 to 9 are :",numbers_negative )
print("The numbers deveided by 2 without reminder are :",devided_by_two)```Out:The positive numbers between -7 to 9 are : [1, 2, 3, 4, 5, 6, 7, 8]The negative numbers between -7 to 9 are : [-7, -6, -5, -4, -3, -2, -1]The numbers deveided by 2 without reminder are : [-6, -4, -2, 0, 2, 4, 6, 8]

总结

其实客观来讲,list在实际项目中所用的地方有限,特别是处理数据量较大的情况下,因为速度极慢,但是在一些边边角角的地方我个人用的还挺多,尤其是不求速度的地方,总的来讲List是我个人比较喜欢的Python
数据结构,简单好用!!!!!

好啦,我要去吃大餐啦,祝大家新年快乐呀!!!

Python 进阶之路 (一) List 进阶方法汇总,新年快乐!相关推荐

  1. 【python】数据挖掘分析清洗——缺失值处理方法汇总

    缺失值处理方法汇总 前言 一.查看缺失值比例 二.基于统计的缺失值处理方法 2.1 删除 2.2 填充固定值 2.3 填充中位数.平均数.众数 2.4 插值法填充,前值或者后值填充 三.基于机器学习的 ...

  2. python npv 计算公式_python数据分析进阶之路(二)----Numpy进阶

    简单应用 矩阵创建及运算 1.手动创建矩阵 np.mat('str') 利用mat('字符串')函数创建矩阵,其中字符串的 表示中,矩阵的行与行之间用分号隔开,行内的元素之间用空格隔开. b = np ...

  3. Android工程师进阶之路 Android开发进阶 从小工到专家 上市啦

    封面 目录1 目录2 - 当当购买链接 - 京东购买链接 为什么写这本书 写这本书的念头由来已久了.也许是从我打算写<Android源码设计模式解析与实战>那时起就萌生了这个念头,因为设计 ...

  4. 好用的python打包软件_Python打包exe文件方法汇总【4种】

    title: Python打包exe文件方法 copyright: true top: 0 date: 2018-08-11 21:08:21 tags: 打包 categories: Python进 ...

  5. python常用内置模块-Python之OS模块常用内置方法汇总

    OS模块的常用内置方法 chdir修改当前工作目录到指定目录 Change the current working directory to the specified path. chmod修改一个 ...

  6. python字符串截取_Python容器类型公共方法汇总

    以下公共方法支持列表,元组,字典,字符串. 内置函数 Python 包含了以下内置函数: 函数描述备注len(item)计算容器中元素个数del(item)删除变量del 有两种方式max(item) ...

  7. Python学习笔记:文件读/写方法汇总

    # ############# 文件操作方法# 重点常用方法标红# ############import time, sys # ########### 读文件 ################### ...

  8. Python获取mp3音频文件时长方法汇总

    '''pymediainfo: pip3 install pymediainfo 版本:5.1.0不支持网络音频 ''' class pymediainfoTest():@classmethoddef ...

  9. python代码提示expected_Expected conditions模块使用方法汇总代码解析

    一.expected_conditions模块是什么? 是Selenium的一个子模块,selenium.webdriver.support.expected_conditions 可以对网页上元素是 ...

  10. Python 进阶之路 (十二) 尾声即是开始

    Python进阶之路总结 大家好,我的<< Python进阶之路>>到这一期就到此为止了,和 <<Python 基础起步>>不同,在掌握了一些基础知识后 ...

最新文章

  1. 关于线程池运行过程中,业务逻辑出现未知异常导致线程中断问题反思
  2. SQL Server 涉及数据库安全常用SQL语句
  3. ubuntu如何安装samba
  4. 深入react技术栈(9):表单
  5. JHChart 1.1.0 iOS图表工具库中文ReadMe
  6. 【题解】(排序) —— POJ 0810:距离排序
  7. SQL_delete删除数据
  8. 《数据结构与算法分析:C语言描述》复习——第六章“排序”——插入排序
  9. 作用域和请求参数传递
  10. bootstrapmodel确认操作框_光伏电站EL检测仪的操作流程
  11. 计算机网络测速创新,一种计算机网络安全测速装置的制作方法
  12. 2020考研初试成绩2月中旬起陆续公布,6点需注意
  13. Landsat 数据集合集(Landsat 5/7/8/9)
  14. Received status code 409 from server: Conflict
  15. gpt分区android系统备份,win10 (GPT+UEFI)利用GHOST进行备份还原系统迁移
  16. MFC 添加静态图片(Picture Control控件)
  17. “黑马程序员”视频学习笔记之面向对象基础及调试问题
  18. awk,gawk调用shell,bash中的变量 笔记221106
  19. asp.net中使用JMail发邮件
  20. 天地图矢量数据下载_全球谷歌卫星地图影像数据下载

热门文章

  1. 集线器和交换机工作原理验证实验
  2. 奥尔良老母鸡成长记之C语言代码运行显示无法启动程序与系统找不到指定文件
  3. SOEM 源码解析 ecx_readODlist
  4. 计算机课word反思,反思Word文档
  5. 高数中反常积分的瑕点是什么?
  6. 利用递归将标签罗列出来
  7. 中职计算机基础教材节选,中职计算机基础 (728)(32页)-原创力文档
  8. PUE是什么?说说数据中心和PUE
  9. AUTOSAR汽车电子嵌入式编程精讲300篇-基于车联网的商用车载终端系统的研究与设计(续)
  10. 使用cookie实现记录浏览商品的过程并能够清空浏览记录(简单的小程序不涉及到数据库的调取)