一、Python 列表(Lists)
- 列表是Python中最基本的数据结构,列表是最常用的Python数据类型
- 列表的数据项不需要具有相同的类型。
- 列表中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推。
Python有6个序列的内置类型,但最常见的是列表和元组。 - 序列都可以进行的操作包括索引,切片,加,乘,检查成员。此外,Python已经内置确定序列的长度以及确定最大和最小的元素的方法。
二、列表的操作
-
创建列表
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"];
list4=[] #空列表
与字符串的索引一样,列表索引从0开始。列表可以进行截取、组合等。
-
访问列表中的值
使用下标索引来访问列表中的值,同样你也可以使用方括号的形式截取字符,如下所示:
#!/usr/bin/python
list1=['physics','chemistry',1997,2000]
list2=[1,2,3,4,5,6,7]
c_list = ['a','b','c',1,2,3,4]
print(list1) ##遍历列表
print('list1[0]:',list1[0])
print('list2[1:5]:',list2[1:5])
print(‘c_list:’c_list[:])
##查看某个元素在这个列表里的个数,如果改元素不存在,那么返回0
print(list1.count('pyhsics'))
##找到这个元素的下标,如果有多个,返回第一个,如果找一个不存在的元素会报错
print(list1.index(1997))
以上实例输出结果:
['physics', 'chemistry', 1997, 2000]
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
0
2
-
更新列表("增"append, extend, insert)
你可以对列表的数据项进行修改或更新,你也可以使用append()方法来添加列表项,如下所示:
实例(Python 3.0+)
#!/usr/bin/python
# -*- coding: UTF-8 -*-
list=[] ##定义一个空列表
list.append('Google') ##使用append()添加元素
list.append('Runoob')
list.insert(1,'Baidu') ##在指定位置添加元素,如果指定的下标不存在,那么就是在末尾添加
print(list)
以上实例输出结果:
['Google', 'Baidu', 'Runoob']
-
删除列表中的元素("删"del、pop、remove)
可以使用 del 语句来删除列表的元素,如下实例:
实例(Python 3.0+)
#!/usr/bin/python
list1 = ['physics', 'chemistry', 1997, 2000]
print (list1)
del list1[2]
print ("After deleting value at index 2 : ")
print (list1)
以上实例输出结果:
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]
- list.pop() #删最后一个元素
- list.pop(n) #指定下标,删除指定的元素,如果删除一个不存在的元素会报错
- list.remove(xx) #删除list 里面的一个元素,有多个相同的元素,删除第一个
- print(list.pop()) #有返回值
- print(list.remove()) #无返回值
- del list[n] #删除指定下标对应的元素
- del list #删除整个列表, list删除后无法访问
-
查找元素("查"in, not in, index, count)
所谓的查找,就是看看指定的元素是否存在
in, not in
python中查找的常用方法为:
- in(存在),如果存在那么结果为true,否则为false
- not in(不存在),如果不存在那么结果为true,否则false
nameList = ['xiaoWang','xiaoZhang','xiaoHua']
findName = input('请输入要查找的姓名:')
if findName in nameList:
print('在字典中找到了相同的名字')
else:
print('没有找到')
- index, count
index和count与字符串中的用法相同
a = ['a', 'b', 'c', 'a', 'b']
a.index('a', 1, 3) # 注意是左闭右开区间
执行结果:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 'a' is not in list
a.index('a', 1, 4)
结果:3
a.count('b')
结果:2
a.count('d')
结果:0
三、python列表脚本操作符
列表对 + 和 * 的操作符与字符串相似。+ 号用于组合列表,* 号用于重复列表。
四、Python列表截取与拼接
Python的列表截取与字符串操作类型,如下所示:
L=['Google', 'Runoob', 'Taobao']
-
操作:
>>>L=['Google', 'Runoob', 'Taobao']
>>> L[2]
'Taobao'
>>> L[-2]
'Runoob'
>>> L[1:]
['Runoob', 'Taobao']
>>>
- 列表还支持拼接操作:
>>>squares = [1, 4, 9, 16, 25]
>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
五、Python列表函数&方法
Python包含以下函数:六、列表常见操作
-
列表排序
注意排序优先级:数字>大写字母>小写字母>符号>中文
- 永久性排序:sort()
- 临时性排序:sorted()
- 反转排序:reverse()
list1 = ["排序","?","123","w","W"]
list2 = ['1','2','3']
a = list1.sort() #永久性排序,就是这个列表就变了
print(list1)
b =sorted(list2) #临时性排序,就是可以赋值某个变量
print(b)
c = list1.reverse()
print(list1)
结果:
['123', '?', 'W', 'w', '排序']
['1', '2', '3']
['排序', 'w', 'W', '?', '123']
-
复制列表-copy()方法
List2=['openstack','云计算','python',"中国","中东",'linux',123,"ww33##"]
list3=List2.copy()
print(List2,list3)
结果:
['openstack', '云计算', 'python', '中国', '中东', 'linux', 123, 'ww33##']
['openstack', '云计算', 'python', '中国', '中东', 'linux', 123, 'ww33##']
注意事项:
List2=['openstack','云计算','python',["中国","中东"],'linux',123,"ww33##"]
list3=List2.copy()
print(List2)
print(list3)
List2[2]="MYSQl DBA"
List2[3][1]="北京"
print(List2)
print(list3)
执行结果:
修改前List2: ['openstack', '云计算', 'python', ['中国', '中东'], 'linux', 123, 'ww33##']
修改前复制list3: ['openstack', '云计算', 'python', ['中国', '中东'], 'linux', 123, 'ww33##']
修改后List2: ['openstack', '云计算', 'mysql dba', ['中国', '北京'], 'linux', 123, 'ww33##']
修改后的list3: ['openstack', '云计算', 'python', ['中国', '北京'], 'linux', 123, 'ww33##']
我们将列表List2中的List2[2]的python和List2[3][1]的中东更改为List2[2]="MYSQl DBA"和List2[3][1]="北京
输出后发现复制的那一部分List2[3][1]复制后是一样的,而List2[2]的值会不一样。主要是内存的地址原因。
同时对这种情况想要复制相同的是不行的
List2=['openstack','云计算','python',["中国","中东"],'linux',123,"ww33##"]
list3=List2
print(List2)
print(list3)
List2[2]="MYSQl DBA"
List2[3][1]="北京"
print(List2)
print(list3)
这里给list3赋值为List2这时会发现更改List2时,会直接更改list3的值
['openstack', '云计算', 'python', ['中国', '中东'], 'linux', 123, 'ww33##']
['openstack', '云计算', 'python', ['中国', '中东'], 'linux', 123, 'ww33##']
['openstack', '云计算', 'MYSQl DBA', ['中国', '北京'], 'linux', 123, 'ww33##']
['openstack', '云计算', 'MYSQl DBA', ['中国', '北京'], 'linux', 123, 'ww33##']
要想复制完全一样的,我们可以导入copy模块
mport copy
List2=['openstack','云计算','python',["中国","中东"],'linux',123,"ww33##"]
list3=copy.deepcopy(List2)
print(List2)
print(list3)
List2[2]="MYSQl DBA"
List2[3][1]="北京"
print(List2)
print(list3)
执行的结果:
['openstack', '云计算', 'python', ['中国', '中东'], 'linux', 123, 'ww33##']
['openstack', '云计算', 'python', ['中国', '中东'], 'linux', 123, 'ww33##']
['openstack', '云计算', 'MYSQl DBA', ['中国', '北京'], 'linux', 123, 'ww33##']
['openstack', '云计算', 'python', ['中国', '中东'], 'linux', 123, 'ww33##']
这时发现,List2元素的值改变不会影响list3的值,下面的这种copy,我们称为deep.copy,而列表的copy()方法是一种浅copy
实战案例
https://blog.csdn.net/Despacito_Kar/article/details/79509042
-
实现功能:
列表为:['Iphone8',6888],['MacPro',14800],['小米6',2499],['Coffee',31],['Book',80],['Nike Shoes',799]
实现一个类似购物车的语句,用户循环输入编号可以将列表内的商品储存到一个新的列表里面,当用户输入'q'时退出循环
-
冒泡排序
def bubble_sort(lists):
len_list=len(lists)
for i in range(len_list):
for j in range(len_list-i-1):
if lists[j]>lists[j+1]:
lists[j],lists[j+1]=lists[j+1],lists[j]
print(lists)
return lists
-
插入排序
def insert_sort(lists):
for i in range(len(lists)):
position=i
while position>0:
if lists[position]<lists[position-1]:
lists[position],lists[position-1]=lists[position-1],lists[position]
position-=1
print(lists)
return lists
-
删除列表中的重复元素
#第一种方式
l=[1,1,6,3,1,5,2]
list(set(l))
#第二种方式
l=[1,1,6,3,1,5,2]
def duplictae(lists):
L=[]
for i in lists:
if i not in L:
L.append(i)
return L
print(duplictae(l))
-
案例1
实现功能:
列表为:['Iphone8',6888],['MacPro',14800],['小米6',2499],['Coffee',31],['Book',80],['NikeShoes',799]
实现一个类似购物车的语句,用户循环输入编号可以将列表内的商品储存到一个新的列表里面,当用户输入'q'时退出循环
实现代码如下:
products = [['Iphone8',6888],['MacPro',14800],['小米6',2499],
['Coffee',31],['Book',80],['Nike Shoes',799]]
shopping_cart = []
while True:
print ('-------------商品列表--------------')
for index,i in enumerate(products):
print ('%s.%s %s'%(index,i[0],i[1]))
choice = input('please input your numbers:')
if choice.isdigit():
choice = int(choice)
shopping_cart.append(products[choice])
elif choice == 'q':
print ('-----------------您以购买如下商品------------')
for index,i in enumerate(shopping_cart):
print ('%s.%s %s'%(index,i[0],i[1]))
break
同时可以添加一个标志位,当用户输入'q'的时候标志位改变while的判断条件,使循环退出,具体代码如下:
products = [['Iphone8',6888],['MacPro',14800],['小米6',2499],
['Coffee',31],['Book',80],['Nike Shoes',799]]
shopping_cart = []
run_flag = True
while run_flag:
print ('-------------商品列表--------------')
for index,i in enumerate(products):
print ('%s.%s %s'%(index,i[0],i[1]))
choice = input('please input your numbers:')
if choice.isdigit():
choice = int(choice)
shopping_cart.append(products[choice])
elif choice == 'q':
print ('-----------------您以购买如下商品------------')
for index,i in enumerate(shopping_cart):
print ('%s.%s %s'%(index,i[0],i[1]))
run_flag = False
-
案例2:(2017-腾讯-在线编程题)
- 题目描述:
给定一个正整数,编写程序计算有多少对质数的和等于输入的这个正整数,并输出结果。输入值小于1000。如,输入为10, 程序应该输出结果为2。(共有两对质数的和为10,分别为(5,5),(3,7)) - 输入描述:
输入包括一个整数n,(3 ≤ n < 1000) - 输出描述:
输出对数 - 示例1 :
输入:10
输出: 2
- 题目描述:
#!/usr/bin/env python
#coding:utf-8
num = input("请输入一个正整数(3 ≤ n < 1000):")
#找出num内的所有质数,并保存在li列表中
li = []
for j in range(2,num):
for i in range(2,num):
i = 2
if j%i !=0:
i += 1
li.append(j)
break
#print li
#找出符合条件质数,输出总对数
p = []
count = 0
for m in li : #m遍历列表li
for n in li[li.index(m):]: #n只遍历在列表li中的m及其后的质数
if n + m == num:
t = (m,n) #数值存在元组
p.append(t) #追加到列表p中
count += 1 #追加一次,加1
print count #输出总对数