200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > Python菜鸟入门:day18编程学习

Python菜鸟入门:day18编程学习

时间:2019-03-31 04:13:05

相关推荐

Python菜鸟入门:day18编程学习

写在前面:

此博客仅用于记录个人学习进度,学识浅薄,若有错误观点欢迎评论区指出。欢迎各位前来交流。(部分材料来源网络,若有侵权,立即删除)

传送门:

day01基础知识

day02知识分类

day03运算符

day04数字与字符串

day05列表

day06元组与字典

day07条件与循环

day08函数概念

day09数据结构

day10模块介绍

day11文件操作

day12编程学习

day13编程学习

day14编程学习

day15编程学习

day16编程学习

day17编程学习

day18编程学习

Python学习:day18

实例编程学习06Python将列表中的指定位置的两个元素对调翻转列表判断元素是否在列表中存在清空列表复制列表计算元素在列表中出现的次数

实例编程学习06

Python将列表中的指定位置的两个元素对调

对调第一个和第三个元素

def swapPositions(list, pos1, pos2):list[pos1], list[pos2] = list[pos2], list[pos1]return listList = [23, 65, 19, 90]pos1, pos2 = 1, 3print(swapPositions(List, pos1-1, pos2-1))

def swapPositions(list, pos1, pos2):first_ele = list.pop(pos1) second_ele = list.pop(pos2-1)list.insert(pos1, second_ele) list.insert(pos2, first_ele) return listList = [23, 65, 19, 90]pos1, pos2 = 1, 3print(swapPositions(List, pos1-1, pos2-1))

def swapPositions(list, pos1, pos2):get = list[pos1], list[pos2]list[pos2], list[pos1] = getreturn listList = [23, 65, 19, 90]pos1, pos2 = 1, 3print(swapPositions(List, pos1-1, pos2-1)

翻转列表

def Reverse(lst):return [ele for ele in reversed(lst)]lst = [10, 11, 12, 13, 14, 15]print(Reverse(lst))

输出结果:

或:

def Reverse(lst):lst.reverse()return lstlst = [10, 11, 12, 13, 14, 15]print(Reverse(lst))

输出结果:

def Reverse(lst):new_lst = lst[::-1]return new_lstlst = [10, 11, 12, 13, 14, 15]print(Reverse(lst))

输出结果:

或直接调用list列表的sort方法,设置reverse为True即可翻转列表:

li = [*range(10, 16)]# 得到列表 li = [10, 11, 12, 13, 14, 15], * 为解包符号print(li)# 降序排列li.sort(reverse = True)print(li)# 输出: [15, 14, 13, 12, 11, 10]

判断元素是否在列表中存在

from bisect import bisect_left # 初始化列表test_list_set = [ 1, 6, 3, 5, 3, 4 ]test_list_bisect = [ 1, 6, 3, 5, 3, 4 ]print("查看 4 是否在列表中 ( 使用 set() + in) : ")test_list_set = set(test_list_set)if 4 in test_list_set :print ("存在")print("查看 4 是否在列表中 ( 使用 sort() + bisect_left() ) : ")test_list_bisect.sort()if bisect_left(test_list_bisect, 4):print ("存在")

输出结果:

清空列表

zack = [6, 0, 4, 1]print('清空前:', zack) RUNOOB.clear()print('清空后:', zack)

输出结果:

复制列表

def clone_runoob(li1):li_copy = li1[:]return li_copyli1 = [4, 8, 2, 10, 15, 18]li2 = clone_runoob(li1)print("原始列表:", li1)print("复制后列表:", li2)

输出结果:

def clone_runoob(li1):li_copy = []li_copy.extend(li1)return li_copyli1 = [4, 8, 2, 10, 15, 18]li2 = clone_runoob(li1)print("原始列表:", li1)print("复制后列表:", li2)

输出结果:

def clone_runoob(li1):li_copy = list(li1)return li_copyli1 = [4, 8, 2, 10, 15, 18]li2 = clone_runoob(li1)print("原始列表:", li1)print("复制后列表:", li2)

输出结果:

计算元素在列表中出现的次数

def countX(lst, x):count = 0for ele in lst:if (ele == x):count = count + 1return countlst = [8, 6, 8, 10, 8, 20, 10, 8, 8]x = 8print(countX(lst, x))

def countX(lst, x):return lst.count(x)lst = [8, 6, 8, 10, 8, 20, 10, 8, 8]x = 8print(countX(lst, x))

end

明天还有最后一天的实训,弄完实训就向爬虫进发,希望明天也能坚持下来吧,加油。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。