Python day05 and day06

Python day05 and day06

list[]列表

list的添加,删除,切片,插入,查找,排序

· 添加

append() 末尾增加一个单独的个体
extend()增加一个可迭代的元素
+号可以添加

list1=[1,3]
list2=[2,4]
print(list1+list2)# [1,3,2,4]
********************
list=[] ||  list=list()   #空列表
list1 = [2, 3, 4]   #列表可添加重复元素
list2=[1,1,2,5]
tuple1=(1,3)
list1.append(2)	#[2, 3, 4, 2]
list1.extend(list2)	#[2, 3, 4, 2, 1, 1, 2, 5]
list1.extend(tuple1)#[2, 3, 4, 2, 1, 3]
*******************************************************************************************

·删除

remove() 删除指定元素
pop() 默认删除最后一个,可以指定索引删除
del() 可以指定索引删除,会删除内容以及地址
clear() 清空

list1 = [2, 3, 4]
list2=[1,1,2,5]
list1.remove(2)			#[3, 4]
list2.pop()  #[1, 1, 2]
list2.pop(2) #[1, 1, 5]
del list1[0] #[3, 4]
del list1 #删除list1及其地址
list1.clear() #[]

. 插入

insert(index,value) 在index处插入value

list1 = [2, 3, 4]
list1.insert(0,1)  #[1, 2, 3, 4]

.查找

index(value,start)从start处查找值为value的位置

list1 = [2, 3, 4,2]
index=list1.index(2)
index1=list1.index(2,1)
print(index,index1)# 0    3

.排序

sort() list.sort()默认升序,想降序就让reversed=True
sorted() //sorted(list)默认升序
reverse() //反转

list1 = [2, 5, 4,1]
list1.reverse()  #[1, 4, 5, 2]
list1.sort() #1, 2, 4, 5]
list1=sorted(list1) #[1, 2, 4, 5]
list1=sorted(list1,reverse=True)#[5, 4, 2, 1]

.count()

查询某个值出现的次数

list1 = [2, 5, 4,1,2,2]
count=list1.count(2)
print(count) #3

.拷贝,赋值

copy()

list1 = [2, 5, 4,1,2,2]
list2=list1  #赋值
print(list1 is list2) ##True 地址是一样的,引用一样的值地址 
list3=list1.copy() #浅拷贝
print(list1 is list3   ##False 地址不一样,各自开辟了一段新的空间存存地址

元组 tumple() 可以有重复元素

元组的添加,删除,查找,count

.添加,删除

都需要转成列表进行列表的添加删除操作后再转成元组,元组没有自己的函数进行这些操作

.查找

index()
用法同lisit一样

tumple=()  || tuple1=tuple()     #空元组
tuple1=(1,2,2,5,3)
index=tuple1.index(2)
index1=tuple1.index(2,2)
print(index,index1)  #1    2

`count()

tuple1=(1,2,2,5,3)
print(tuple1.count(2)) #2

元组与列表间的转换

list1=list(tumple)

tumple1=tumple(list1)

.切片(同字符一样串)

list1 = [2, 5, 4,1,2,2] 
print(list1[:])#[2, 5, 4, 1, 2, 2]
tuple1=(1,2,2,5,3)
print(tuple1[:])#(1, 2, 2, 5, 3)

集合set() 无序列表,且不能有重复元素

set0=set() #空集合  不可以是set={},这是字典类型
set1={1,3,5,7,9}
print(set1,type(set1))  #{1, 3, 5, 7, 9} <class 'set'>

. 添加,删除,copy()

add()添加指定元素
remove() 没有会报错
discard()删除指定元素,没有不会报错
pop() 默认删除第一个
clear()

set1={1,3,5,7,9}
set1.add(2) #{1, 2, 3, 5, 7, 9}
set1.remove(3) #{1, 5, 7, 9}
set1.discard(3)#{1, 5, 7, 9}
set1.pop() #{3, 5, 7, 9}

.update(可迭代)

list1=[1,2,3]
set1={1,3,5,7,9}
set1.update(list1) #必须加可迭代的
print(set1)#{1, 2, 3, 5, 7, 9}

.&(交集), ^(对称差集), |(并集),set1-set2(差集)

方法交集:intersection()
方法差集:difference()
方法并集:union()
方法对称差集:symmetric_difference()

set1={1,3,5,7,9}
set2={1,2}
********************交集***************************
print(set1.intersection(set2)) #{1}
print(set1 & set2) #{1}
*******************并集***************************
print(set2 | set1) #{1, 2, 3, 5, 7, 9}
print(set1.union(set2))#{1, 2, 3, 5, 7, 9}
********************差集***************************
print(set1.difference(set2)) #{9, 3, 5, 7}
print(set2.difference(set1)) #{2}
print(set1 - set2) #{9, 3, 5, 7}
print(set2 - set1)#{2}
********************对称差集***************************
print(set1.symmetric_difference(set2))#{2, 3, 5, 7, 9}
print(set1 ^ set2) #{2, 3, 5, 7, 9}


.list,tumple转化

set1={1,3,5,7,9}
set2={1,2}
print(list(set2),tuple(set1))`			#[1, 2] 		(1, 3, 5, 7, 9)
list1=[1,3,5,7]
tuple1=(1,3,5,7)
print(set(list1),set(tuple1))   #{1, 3, 5, 7}			 {1, 3, 5, 7}

.字典dict(), 键值对

.添加,修改

dict1 = {'s': 1, 's1': 1}
dict1['a']='10' #{'s': 1, 's1': 1, 'a': '10'} 若字典中没有该key,会创建一个键值对加入里面
dict1['a']='20' #{'s': 1, 's1': 1, 'a': '20'} 若字典中已存在该KEY,相当于修改,覆盖原先的value

.values(),keys(),copy()

dict1 = {'s': 1, 's1': 1}
dict1['a']='10'
dict1['a']='20'
a=list(dict1.keys()) #['s', 's1', 'a'] 输出所有key,存在列表中	
a=dict1.values()  #dict_values([1, 1, '20']) #输出所有value存储在列表中
a=list(dict1.values()) #[1, 1, '20']

.删除

pop() pop() 方法删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。
clear()

dict1 = {'s': 1, 's1': 1}
dict1['a']='10'
dict1['a']='20'
dict1.pop('s')  #删除指定key元素
print(dict1) #{'s1': 1, 'a': '20'}
dict1.clear() #{}

get()------fromkeys()--------update()---------popitem()--------items()------setdefault(key, default=None)

dict1 = {'s': 1, 's1': 1}
dict1['a']='10'
dict1['a']='20'
a=dict1.get('s')
print(a) #1,得到指定key对应的value     get(),若key不存在返回默认值
a=dict1.get('b')
print(a)#None
*****************************************************
dict1 = {'s': 1, 's1': 1}          fromkeys() 创建一个新字典,以序列 seq 中元素做字典的键,value 为字典所有键对应的初始值
dict1['a']='10'
dict1['a']='20'
seq = ('name', 'age', 'sex')
a=dict1.fromkeys(seq)
print(a)  #{'name': None, 'age': None, 'sex': None}
a=dict1.fromkeys(seq,10)
print(a) #{'name': 10, 'age': 10, 'sex': 10}
******************************************************************************
															update()
dict = {'Name': 'Runoob', 'Age': 7}
dict2 = {'Sex': 'female' }
dict.update(dict2)
print (dict) # {'Name': 'Runoob', 'Age': 7, 'Sex': 'female'}
*******************************************************************************
					popitem() popitem() 方法随机返回并删除字典中的一对键和值(一般删除末尾对)。
site= {'name': '菜鸟教程', 'alexa': 10000, 'url': 'www.runoob.com'}
pop_obj=site.popitem()
print(pop_obj)   
print(site) 	             #  ('url', 'www.runoob.com')
							{'name': '菜鸟教程', 'alexa': 10000}
***************************************************************************
items()方法以列表返回可遍历的(,) 元组数组。
dict = {'Name': 'Runoob', 'Age': 7}
print(dict.items()) #dict_items([('Age', 7), ('Name', 'Runoob')])
****************************************************************************
setdefault(key, default=None)和 get()方法 类似, 如果键不已经存在于字典中,将会添加键并将值设为默认值
dict = {'Name': 'Runoob', 'Age': 7}
 
print (dict.setdefault('Age', None)) #7
print (dict.setdefault('Sex', None)) #None

.list,tumple转化(只有key存入表中)

dict = {'Name': 'Runoob', 'Age': 7}
list1=list(dict)
print(list1) #['Name', 'Age'] 
tuple1=tuple(dict)
print(tuple1) #('Name', 'Age')

***********************************
tumple1=(1,3,4,5,6)
dict1={'a':1}
dict1[list2]=2#报错,列表不能存到key中
dict1[tumple1]=3
dict1[5]=4
dict1[set1]=5#报错,集合不能存到key中
print(dict1)

其他

**************直接交换方式*************
x,y=1,2
x,y=y,x
print(x,y) #2 1
***********遍历字典只能输出key******
dict1 = {'Name': 'Runoob', 'Age': 7}
for i in dict1:
    print(i)                      #Name
								#Age
	

.用字典写一个图书借还系统

import time

print('*' * 50)
print('------------图书馆--------------')
print('*' * 50)

# 图书馆的书籍定义
# books = [['防脱发指南', 5], ['颈椎康复指南', 3], ['python从入门到跑路', 6], ['活着', 4], ['追妹攻略', 4]]
books = {'防脱发指南': 5, '颈椎康复指南': 3, 'python从入门到跑路': 6, '活着': 4, '追妹攻略': 4}
# 学生借书容器
student_books = {}
student_book=[]
while True:

    choice = input('请选择功能: 1.查询书籍 2.借书 3.还书 4.显示所有书籍 5.根据用户用户名查询书籍 6.退出系统:')
    if choice == '1':
        # 查询书籍
        print('--------查询书籍---------')
        search_book = input('请输入要查询的书籍名称:')
        # 遍历books
        for book in books:
            if search_book in book:  # ‘活着’ in ['活着',5]  ---》True
                print('查询的书籍名称是:{},可借数量:{}'.format(book, books.get(search_book)))
                break
        else:
            print('本图书馆不存在此书!')

    elif choice == '2':
        # 借书
        print('-------------借书功能--------------')
        username = input('输入用户名:')
        flag = True
        while flag:
            book_name = input('输入书名:')
            # 查询
            for book in books:
                if book_name in book:  # ‘活着’ in ['活着',5]  ---》True
                    print('查询的书籍名称是:{},可借数量:{}'.format(book, books.get(book)))
                    # 判断可借数量
                    value = books.get(book)
                    if books[book_name] > 0:
                        # 可以借书:
                        for stubooks in student_books:
                            if username in stubooks:  # stubooks --->{'tom':[‘’,‘’]}
                                # 说明用户借过书
                                if book_name in student_books.get(stubooks):  # ‘活着’in {‘活着’,[‘’,‘’]}
                                    print('已经借过此书!不能再借!')
                                else:
                                    # student_books[stubooks] = book_name
                                    student_book.append(book_name)
                                    student_books[username]=student_book
                                    # 减少数量
                                    books[book_name] -= 1
                                    flag = False
                                    print('借书成功!')
                                # 退出
                                break
                        else:
                            # 此人从来没有在图书馆借书
                            # 构建结构: ['人名',{'',''}]
                            # 将其添加到student_books
                            # student_books[username] = book_name
                            student_book.append(book_name)
                            student_books[username]=student_book
                            # 改变可借数量
                            books[book_name] -= 1
                            print(value)
                            flag = False
                            print('借书成功!')
                    break
            else:
                print('本图书馆不存在此书!重新输入书名!')

    elif choice == '3':
        # 还书
        print('----------还书功能-----------')
        username = input('输入用户名:')
        book_name = input('输入要还的书籍名称:')
        # 开始遍历
        for stubooks in student_books:
            if username in stubooks:
                # 说此人借过书
                if book_name in student_books[username]:
                    # 说明借过此书
                    student_books.pop(stubooks)
                    # 修改数量
                    for book in books:
                        if book_name in book:
                            books[book_name] += 1
                            break
                    # 还书成功
                    print('成功归还')

                else:
                    print('没有借过此书!')
                # 跳出
                break
        else:
            print('查无此用户,{}是否还没有借书?'.format(username))

    elif choice == '4':
        # 显示所有书籍
        print('----------图书馆所有书籍如下:--------------')
        print('书名:\t数量:')
        for book in books:
            print(book, books[book])
    elif choice == '5':
        print('---------根据人名查询数据------------')
        username = input('输入人名:')
        for stubooks in student_books:
            if username in stubooks:
                print('{}所借的书籍如下:\t{}'.format(username, student_books[username]))
                # 遍历打印所借书籍
                # for index, book_name in enumerate(stubooks[1]):  # (index,value)
                #     print('{}: {}'.format(index + 1, book_name))
                # 退出
                break
        else:
            print('{}用户还没有借过书!'.format(username))

    elif choice == '6':
        answer = input('确定要退出图书管理系统吗?(yes/no)')
        if answer.lower() == 'yes':
            print('即将退出系统....')
            time.sleep(1)
            print('系统关闭,欢迎下次使用....')
            break

    else:
        print('输入错误请重新输入....')


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值