1.元祖
元祖不能修改,没有增删改查的方法。有count和index。
>>> a=()
>>> a=(1,)
>>> type(a)
<class 'tuple'>
>>> a=1,2,3 #不写括号的方式也可以
>>> type(a)
<class 'tuple'>
>>> a=[1,2]
>>> a=tuple(a) #将list转化为元祖
>>> a
(1, 2)
- 元祖访问、遍历(也可以切片)
>>> tup1 = ('physics', 'chemistry', 1997, 2000)
>>> tup2 = (1, 2, 3, 4, 5, 6, 7 )
>>> tup1[2:4]
(1997, 2000)
>>> tup2[3]
4
>>> for i in tup1:
... print (i)
...
physics
chemistry
1997
2000
- 运算
>>> a=(1,2)
>>> b=(3,4)
>>> a+b
(1, 2, 3, 4)
>>> len(a)
2
>>> a*4
(1, 2, 1, 2, 1, 2, 1, 2)
>>> 1 in a
True
>>> a,b=a
>>> a
1
>>> b
2
>>> a=(1,2,3,4,5)
>>> max(a)
5
>>> min(a)
1
>>> tuple("hello")
('h', 'e', 'l', 'l', 'o')
- 元组中的可变对象可以修改
>>> a
(1, 2, 3, 4, 5)
>>> a=(1,2,3,[1,2],5)
>>> a[3][0]=2
>>> a
(1, 2, 3, [2, 2], 5)
2.字典
key为不可变类型、不能重复。
>>> d={}
>>> type(d)
<class 'dict'>
>>> isinstance(d,dict)
True
>>> d={1:"2",2:2,3:[1,2]}
#key必须为不可变类型
>>> d["hello"]='hello'
>>> d
{1: 'hello', 2: 2, 3: [1, 2], 'hello': 'hello'}
>>> d[[1]]="e"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> d[(1,)]="e"
>>> d
{1: 'hello', 2: 2, 3: [1, 2], 'hello': 'hello', (1,): 'e'}
>>> d
{'Name': 'Zara', 'Age': 7, 'Class': 'First'}
>>> d.keys()
dict_keys(['Name', 'Age', 'Class'])
>>> d.values()
dict_values(['Zara', 7, 'First'])
>>> d.items()
dict_items([('Name', 'Zara'), ('Age', 7), ('Class', 'First')])
- 利用不能重复可排重,set也能排重
>>> a=[1,2,3,1,2,3,3]
>>> d={}
>>> for i in a:
... d[i]=i
...
>>> d
{1: 1, 2: 2, 3: 3}
>>> list(d.keys())
[1, 2, 3]
>>> set(a)
{1, 2, 3}
- 练习:统计其中所有的数字出现的次数
s="I am a 19 years old,you are 10!"
#请统计所有的数字出现的次数,用字典储存
result={}
for i in s:
if i>="0" and i<="9" :
if i in result.keys():
result[i]+=1
else:
result[i]=1
print(result)
#结果:
#{'1': 2, '9': 1, '0': 1}
import string
s="I am a 19 years old,you are 10! 19years,123 years!"
#请统计所有的数字出现的次数,用字典储存
new_s=""
for i in s:
if i in string.digits: #都将字母和字符串都转化为空格,排除干扰
new_s+=i
else:
new_s+=" "
print(new_s)
result={}
for i in new_s.split():
if i.isdigit() :
if i in result.keys():
result[i]+=1
else:
result[i]=1
print(result)
#结果:
#{'19': 2, '10': 1, '123': 1}
- 字典删除
>>> d = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
>>> del d["Name"] #删除单一元素
>>> d
{'Age': 7, 'Class': 'First'}
>>> d.clear() #清空所有内容
>>> d
{}
>>> del d #删除元祖
>>> d
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined
练习:
d={"a0":100,"b1":200,"c":"300"}
#统计一下一同出现多少个0
s=str(d)
new_s=list(s)
d={}
for i in new_s:
if i in d.keys():
if i =="0":
d[i]+=1
else:
d[i]=1
print(d["0"])
print(d)
#print(str(d).count("0"))
'''
d={"a0":100,"b1":200,"c":"300"}
#统计一下一同出现多少个0
s=str(d)
new_s=list(s)
result=0
for i in new_s:
if i =="0":
result+=1
print(result)
'''
-
字典排序:字典没有排序,是散列。
字典的查找比list快,哈希算法。
sorted(iterable [, key[, reverse]] )
(1)iterable:是可迭代类型类型;
(2)key:用列表元素的某个属性和函数进行作为关键字,有默认值,迭代集合中的一项;
(3)reverse:排序规则. reverse = True 或者 reverse = False,有默认值,默认为升序排列(False)。
#一个字符串排序,排序规则:小写<大写<奇数<偶数。
# 原理:先比较元组的第一个值,FALSE<TRUE,如果相等就比较元组的下一个值,以此类推。
# 先看一下Boolean value 的排序:
# print(sorted([True,Flase]))===>结果[False,True]
# Boolean 的排序会将 False 排在前,True排在后 .
s='9a13C85c7B24A6b' #正确的顺序应该为:abcABC135792468
lis=sorted(s,key=lambda x:(x.isdigit(),x.isdigit() and int(x)%2==0,x.isalpha() and x.isupper(),x.isalpha() and x.islower()))
print(''.join(lis))
# 1.x.isdigit()的作用是把数字放在前边,字母放在后边.
# 2.x.isdigit() and int(x) % 2 == 0的作用是保证奇数在前,偶数在后。
# 3.x.isupper()的作用是在前面基础上,保证字母小写在前大写在后.
# 4.最后的x表示在前面基础上,对所有类别数字或字母排序。
字典常用函数
>>> d={"1":"a","2":"b","3":"c"}
>>> print (d.get("1","key not found"))
a
>>> print(d.get("4"))
None
>>> print(d.get("4","hello")) #存在则返回值,不存在返回None,或提示
hello
>>> d={"1":"a","2":"b","3":"c"}
>>> d.setdefault("1","xx") #存在即返回
'a'
>>> d.setdefault("4","d") #若字典中的key不存在,则生成key,并使用默认值赋值
'd'
>>> print (d)
{'1': 'a', '2': 'b', '3': 'c', '4': 'd'}
>>> d=dict(red=1,blue=2) #快速创建字典
>>> d
{'red': 1, 'blue': 2}
>>> data=dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> data
{'one': 1, 'two': 2, 'three': 3}
>>> data=dict([('one', 1), ('two', 2), ('three', 3)])
>>> data
{'one': 1, 'two': 2, 'three': 3}
>>> d=d.fromkeys([1,2,3]) #用fromkeys创建字典
>>> d
{1: None, 2: None, 3: None}
>>> d=d.fromkeys([1,2,3],"x")
>>> d
{1: 'x', 2: 'x', 3: 'x'}
>>> d=dict([(1,"a"),(2,"b")])
>>> d
{1: 'a', 2: 'b'}
>>> d.update({1:"XX"}) #update,若key存在,则直接更新key对应的value
>>> d
{1: 'XX', 2: 'b'}
>>> d.update({10:"XX"}) #若不存在key,则增加key和value
>>> d
{1: 'XX', 2: 'b', 10: 'XX'}
>>> a={1:'a',2:"b",3:"c"}
>>> print (a.popitem()) #popitem 随机返回并删除字典中的一对键和值。
(3, 'c')
>>> print (a)
{1: 'a', 2: 'b'}
>>> a={1:'a',2:"b",3:"c"}
>>> print (a.popitem())
(3, 'c')
>>> print (a)
{1: 'a', 2: 'b'}
>>> a={1:"a",2:"b",3:"c"}
>>> print (a.pop(1))
a
>>> print (a.pop(4,"default value"))
#删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。
default value
>>> print (a)
{2: 'b', 3: 'c'}
练习:图书馆
welcome_info="""
欢迎使用图书馆系统
读书改变命运!
可以输入命令:
edit/list/exit
"""
def show_welcome_info():
global welcome_info
print(welcome_info)
def edit_book_info():
global books_info
global no
no+=1
book_id=no
books_info[book_id]={}
book_name=input("请输入图书名字:")
book_author=input("请输入作者名字:")
books_info[book_id]["book_name"]=book_name
books_info[book_id]["book_author"]=book_author
def get_all_books_info():
global books_info
for key,value in books_info.items():
print("书的编号:",key)
print("书的名字:",value["book_name"])
print("书的作者:",value["book_author"])
print("*"*20)
no=0
books_info={} #存书
edit_book_info()
edit_book_info()
get_all_books_info()
print(books_info)
"""
show_welcome_info() #调用欢迎语
while 1:
command =input("请输入你的命令:")
if command == "edit":
edit_book_info()
elif command=="list":
get_all_books_info()
elif command =="exit":
break
"""