码迷,mamicode.com
首页 > 编程语言 > 详细

Python 列表(数组)初识

时间:2018-12-19 21:59:11      阅读:272      评论:0      收藏:0      [点我收藏+]

标签:col   正序   red   gre   默认   remove   color   pytho   sorted   

1 声明列表

names =["tome","jonson","black"]
print(names)

2 访问列表元素

names = ["tomy","jonson","black"]
print(names[0])
#访问列表最后一个元素,使用-1下标
names = ["tomy","jonson","black"]
print(names[-1])

3 修改,添加,删除元素

#修改元素
names = ["tomy","jonson","black"]
print(names)
names[1] = "france"
print(names)
names = ["tomy","jonson","black"]
print(names)
#在列表末尾追加元素
names.append("masa")
print(names)
#在列表中插入元素
names.insert(2,"jaray")
print(names)
names = ["tomy","jonson","black"]
print(names)
#使用del删除元素
del names[1]
print(names)

names.insert(1,"jonson")
print(names)

#使用pop删除元素,pop可以弹出这个元素
#不使用参数的话,默认弹出最后一个元素
popped_name = names.pop()
print(popped_name)
print(names)
#弹出指定位置元素
first_name = names.pop(0)
print(first_name)
print(names)

names.append("yellow")
names.append("red")
names.append("jonson")
print(names)

#根据指定值删除元素,如果列表中有多个相同的值,remove只删除第一个符合的值
names.remove("jonson")
print(names)

 4 使用sort对列表进行永久性排序

names = ["red","orange","yellow","green","blue"]
print(names)
#正序
names.sort()
print(names)
#倒序
names.sort(reverse=True)
print(names)

#中文排序貌似不好用,网上搜索结果是需要安装中文库,以后有时间再研究,研究明白后追加到这里面
names = ["张三","李四","王五","赵六","马七"]
print(names)
names.sort()
print(names)

5 使用sorted对列表进行临时性排序

names = ["red","orange","yellow","green","blue"]
#正序
print(sorted(names))
print(names)
#倒序
print(sorted(names,reverse=True))
print(names)

6 反转列表元素排列顺序

names = ["red","orange","yellow","green","blue"]
#反转
names.reverse()
print(names)
#再次调用,又反转回来
names.reverse()
print(names)

7 获取列表长度

names = ["red","orange","yellow","green","blue"]
print(len(names))

 

Python 列表(数组)初识

标签:col   正序   red   gre   默认   remove   color   pytho   sorted   

原文地址:https://www.cnblogs.com/liyunfei0103/p/10145883.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!