python列表
一、列表的创建与操作
1.创建列表
a = [] ##元素类型可为int,float,complex,str,list,tuple
b = [a, 1, True, 3j + 2, "hi"]
c = [[1, 2, 3, 4], [a, b], 233, "hello"]
d = [a, b, c ]
2.列表的索引与切片
>>> c = [[1, 2, 3, 4], [5,6], 233, "hello"]
>>> c
[[1, 2, 3, 4], [5, 6], 233, 'hello']
>>> type(c) ##显示类型
<class 'list'>
>>> c[0][-1]
4
>>> c[-1][3]
'l'
>>> c[-2]
233
3.强制转换
>>> s=list(range(5)) ##采用内置方法list()强制转换
>>> s
[0, 1, 2, 3, 4]
>>> s[3]
3
4.列表的重复
>>> list=['a',3,True,'hello']
>>> list*3
['a', 3, True, 'hello', 'a', 3, True, 'hello', 'a', 3, True, 'hello']
5.列表的成员操作符
>>> list
['a', 3, True, 'hello']
>>> 'a' in list ##判断元素是否在列表中
True
>>> 'test' in list
False
>>> True in list
True
6.列表的连接
>>> list1=[1,3,5,'hello']
>>> list2=[2,4,'test']
>>> list1+list2 ##连接成一个列表
[1, 3, 5, 'hello', 2, 4, 'test']
二、列表的编辑
1.添加元素 append 和 extend
append:添加元素,默认添加到最后
>>> list = [ 'a','b','c','a','e','b']
>>> list.append('f')
>>> print(list)
['a', 'b', 'c', 'a', 'e', 'b', 'f']
extend :将新列表元素全部添加
>>> nal=['a','b','c']
>>> list.extend(nal)
>>> list
['a', 'b', 'c', 'a', 'e', 'b', 'a', 'b', 'c']
如果用append添加列表,则:
>>> lan.append(nal) ##将列表作为元素添加
>>> lan
['a', 'b', 'c', 'a', 'e', 'b', ['a', 'b', 'c']]
2.删除 remove 、pop 和 del(可删除列表) clear(清空列表)
remove:
>>> lan.remove(['a','b','c']) ##移除指定元素
>>> lan
['b', 'c', 'a', 'e', 'b']
pop:
>>> lan
['b', 'c', 'a', 'e', 'b']
>>> lan.pop(1) ##删除索引的元素,并返回索引值
'c'
>>> lan
['b', 'a', 'e', 'b']
del:
>>> lan
['b', 'a', 'e', 'b', 'f', 'a', 'b', 'c']
>>> del lan[-1] ##删除指定元素
>>> lan
['b', 'a', 'e', 'b', 'f', 'a', 'b']
>>> del lan [:-4] ##除了最后4的元素全删除
>>> lan
['b', 'f', 'a', 'b']
>>> del lan[2:] ##从第2个索引开始全删除
>>> lan
['b', 'f']
3.插入 insert
>>> lan
['b', 'f']
>>> lan.insert(0,'s') ##插入到索引值前
>>> lan
['s', 'b', 'f']
4.统计次数 count
>>> lan
['s', 's', 's', 'b', 'f']
>>> lan.count("s") ##统计s出现的次数
3
5.修改(重新赋值)
>>> s
['a', 'e', 'i', 'o', 'u']
>>> s[0]='x' ##索引修改
>>> s
['x', 'e', 'i', 'o', 'u']
6.索引 index
>>> s=['a','e','i','o','u']
>>> s.index('i') ##输出对应的元素
2
>>> s.index('e')
1
7.排序 sort
>>> s
['x', 'e', 'i', 'o', 'u']
>>> s.sort() ##正序,按ASCII码大小排列
>>> s
['e', 'i', 'o', 'u', 'x']
>>> s
['e', 'i', 'o', 'u', 'x']
>>> s.sort(reverse=True) ##倒序,注意:reverse默认为False
>>> s
['x', 'u', 'o', 'i', 'e']
>>> s
['x', 'u', 'o', 'i', 'e']
>>> s[::-1] ##倒序
['e', 'i', 'o', 'u', 'x']
随机排列
In [20]: import random ##导入random模块
In [29]: a
Out[29]: [1, 2, 3, 4, 6, 7, 9]
In [30]: random.shuffle(a)
In [31]: a
Out[31]: [2, 9, 6, 1, 4, 3, 7]
In [32]: a.sort()
In [33]: a
Out[33]: [1, 2, 3, 4, 6, 7, 9]
8.反转 reverse
>>> s
['x', 'u', 'o', 'i', 'e']
>>> s.reverse()
>>> s
['e', 'i', 'o', 'u', 'x']
9.复制 copy
In [14]: a
Out[14]: [[0, 2, 3, 4], '1', 'x', 2]
In [15]: b=copy.copy(a) ##浅拷贝
In [16]: id(a),id(b) ##注意:a,b列表的地址不同,但列表中"列表"元素地址相同
Out[16]: (41887432, 42230920)
In [17]: id(a[0]),id(b[0])
Out[17]: (41887360, 41887360)
练习:将用户列表与密码列表一一匹配登陆,若用户不存在、密码错误则提示报错;三次登陆机会!
user = ['root', 'student', 'westos']
passwd = ['redhat', 'hello', 'lee']
for i in range(3):
USER = input("please input username:")
PASS = input("please input passwd:")
if USER in user:
n = user.index(USER)
if PASS == passwd[n]:
print("Login successfully")
break
else:
print("Login failly")
else:
print(USER + " is not exist")
continue
else:
print("ERROR:Time is over")
注意:若密码加密,需导入getpass模块,且该模块只能在命令行执行!!
# import getpass ##加密模块,只能在终端中的命令行执行!
#
# PASS = getpass.getpass()
三、构建队列与栈数据结构
1.简单队列结构构建(特点:先进先出)
menu = """
Operation
1). In
2). Out
3). First element
4). Last element
5). length
6). View
Please input you option: """
list = ['a','1']
choice = input(menu)
if choice == "1":
print("In Queue".center(30, "*"))
item = input("The Element:")
if len(list) < 4: ##判断队列是否已满
list.append(item) ##添加元素
print(item + " is APPEND ok!")
print("New list is : %s" %(list))
else:
print("The Queue is full!")
elif choice == "2":
print("Out Queue".center(30, "*"))
if not list: ##判断队列是否为空
print("The Queue is empty!")
else:
N = list.pop(0) ##队首元素出队
print(N + " is POP ok!")
elif choice == "3":
print("FIRST Queue".center(30, "*"))
if not list:
print("The Queue is empty!")
else: ##显示队首元素
print("FIRST: "+list[0])
elif choice == "4":
print("LAST Queue".center(30, "*"))
if not list:
print("The Queue is empty!")
else: ##显示队尾元素
print("LAST: "+list[-1])
elif choice == "5":
print("LEN Queue".center(30, "*"))
print("The LEN : %s" %(len(list))) ##显示队列长度
elif choice == "6":
print("VIEW Queue".center(30, "*"))
if not list:
print("The Queue is empty!")
else: ##显示队列元素,可直接打印,也可遍历列表
print("Element are :",end=" ")
for item in list:
print(item,end=",")
else:
print("ERROR!!!")
2. 简单构建栈数据结构(特点:先进后出)
menu = """
Operation
1). In
2). Out
3). First element
4). length
5). View
Please input you option:
"""
stack=[1,'4','w',3]
choice=input(menu)
if choice=='1':
print('In Stack'.center(20,'*'))
item=input('The Element:')
if len(stack)< 4: ##判断栈是否已满
stack.append(item) ##添加元素
print('%s is append ok!' %(item))
print('New_stack is : %s' %(stack))
else:
print("The stack is full!")
elif choice=='2':
print('Out Stack'.center(20,'*'))
if not stack: ##判断栈是否为空
print('The Stack is empty!')
else: ##栈尾元素出栈
N = stack.pop(-1)
print('%s is pop ok!' %(N))
elif choice=='3':
print('The First Stack'.center(20,'*'))
if not stack:
print("The Stack is empty!")
else:
print('The First is: %s' %(stack[0]))
elif choice=='4': ##显示栈的长度
print('The Lenth Stack'.center(20,'*'))
print('The Len is: %s' %(len(stack)))
elif choice=='5':
print('View Stack'.center(20,'*'))
if not stack:
print("The Stack is empty!")
else: ##显示栈元素,可遍历,也可打印列表
for item in stack:
print(item,end=',')
else:
print('ERROR!')
四、拓展
1.is和==的区别
is:数据类型,大小,节点(地址)必须一致!
==:数据类型和大小一致即可 #####2.深拷贝与浅拷贝
2.深拷贝与浅拷贝
浅拷贝:
In [14]: a
Out[14]: [[0, 2, 3, 4], '1', 'x', 2]
In [15]: b=copy.copy(a)
In [16]: id(a),id(b)
Out[16]: (41887432, 42230920)
In [17]: id(a[0]),id(b[0]) ##'列表'元素的地址相同
Out[17]: (41887360, 41887360)
深拷贝:
In [18]: b=copy.deepcopy(a) ##需导入deepcopy模块
In [19]: id(a[0]),id(b[0]) ##'列表'元素的地址不同
Out[19]: (41887360, 42262328)
3.可变与不可变数据类型
不可变数据类型: int,bool,float,str
可变数据类型: list,tuple等,可以增删改查
元组
一.元组的定义
>>> s = (1,2,3,4)
>>> type(s) ##查看s类型
<class 'tuple'>
>>> a=(1) ##注意:此定义方式为int型,非tuplexing
>>> type(a)
<class 'int'>
>>> b=(1,) ##用','隔开即可定义为tuplexing
>>> type(b)
<class 'tuple'>
二.元组的操作
1.元组的索引与切片
>>> s[:-1] ##除了最后一个元素都显示
(1, 2, 3)
>>> s
(1, 2, 3, 4)
>>> s[1:] ##索引值1之后的元素均显示
(2, 3, 4)
>>> s[::-1] ##倒序排列元组
(4, 3, 2, 1)
2.元组的重复
>>> S = s*3
>>> S
(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4)
3.元组的循环
>>> for index,value in enumerate(s):
... print(index,value)
...
0 1
1 2
2 3
3 4
4.元组的复制
>>> t=('python','shell')
>>> print('first is %s,second is %s' %t)
first is python,second is shell
>>> x,y=10,20
>>> x,y=y,x ##注意:若是java或c语言,必须有中间变量
>>> x,y
(20, 10)
5.列表的排序与掐头去尾
>>> scores
[78, 87, 89, 98, 90, 85]
>>> scores.sort()
>>> scores
[78, 85, 87, 89, 90, 98]
>>> min_score,*middle,max_score=scores
>>> min_score
78
>>> max_score
98
>>> sum(middle)
351
注意:python2中不能识别
In [4]: li=[45,43,89,75,17]
In [5]: li.sort()
In [6]: min,*middle,max=li
File "<ipython-input-6-813e08f9652f>", line 1
min,*middle,max=li
^
SyntaxError: invalid syntax
集合
注意:定义空集合:set()!!
1.交集
a = {1, 2}
b = {1, 2, 3, 4}
print(a & b)
print(a.intersection(b))
print(a.isdisjoint(b)) ##判断a和b有没有交集,没有为True,否则为False;
2.合集
a = {1, 2}
b = {3, 4}
print(a | b ) ##两种方式均可
print(a.union(b))
3.差集
a = {1, 2}
b = {1,2,3, 4}
print(b - a) ##两种方式均可
print(b.difference(a))
4.对差等分:列举两集合不同的元素
a = {1, 2,3}
b = {1,3,4}
print(a^b) ##结果{2,4},两种方式均可
print(a.symmetric_difference(b))
5.子集、父集
a = {1, 2,}
b = {1,2,3,4}
print(a.issubset(b)) ##判断a是b的子集吗?是则返回True,否则返回False
print(b.issuperset(a)) ##判断b是a的父集吗?是则返回True,否则返回False