Python学习笔记_week2_列表、元组、字典、字符串、文件、i编码

时间:2021-04-02 14:42:46

一、 列表、元组

 names=["A","B","C","D"]
print(names)
print(names[0],names[2])
print(names[1:3]) # 包括起始位置,不包括结束位置,顾头不顾尾。这个动作叫切片。
print(names[-1])
print(names[-1:-3]) # 切片从左到右
print(names[-2:]) # 取到最后
print(names[:3]) #从0取可以不写 names.append("E") #追加
print(names) names.insert(1,"F") #插入,1表示插入的位置 只能一个一个来,不能批量插入
print(names)
names.insert(3,"G")
print(names) names[2]="H" # 改
print(names) #delete
'''names.remove("F")
print(names)'''
'''del names[1]
print(names)'''
'''names.pop(1) # 不输入下标删掉最后一个'''
print(names)
print(names.index("H"))
print(names[names.index("H")]) names.append("A") # 可以重名
print(names.count("A")) '''names.clear() # 清空
print(names)''' names.reverse()
print(names) #反转 names.sort() #排序:#!>1>C>c 按ASCII码排序来的
print(names) names2=[1,2,3,4]
names.extend(names2) #并过来
print(names,names2)
del names2 #删除列表names2,print(names2)报错
print(names) names3=names.copy() #复制
print(names3) names[2]="三"
print(names)
print(names3)

names_list

 import copy

 names=["A","B","C",["E","F"],"D"]
print(names) names2=copy.deepcopy(names) #copy.copy(names)和浅copy一样,深copy用处不大,知道就行
print(names,names2,sep="\n")
print(id(names),id(names2),sep="\n") names[3][0]="MM"
print(names,names2,sep="\n")

names_copy

 names=["A","B","C",["E","F"],"D"]
print(names) names2=names.copy() #names2=name还跟简单的str和数字不同,names2跟着names变
print(names2) names[2]="三"
print(names,names2,sep="\n") names[3][0]="MM"
print(names,names2,sep="\n") #只copy第一层 ,改names2也一样 names2[3][0]="GG"
print(names,names2,sep="\n")

sublist_names

 names=["A","B","C",["M","G"],"D","E"]

 for i in names:
print(i) #切片
#range(1,10,2)
print(names[0:-1:2])
print(names[::2])
print(names[:])

loop_sec_names

test.py:1、sys模块是Python解释器自带的用C语言写的,所以找不到。2、浅copy是引用列表。

 import copy
person=["name",["salary",100]] '''p1=copy.copy(person)
p2=person[:]
p3=list(person)
print(p1,p2,p3,sep="\n")'''#三种浅copy方法 p1=person[:]
p2=person[:] p1[0]="alex"
p2[0]="fengjie" p1[1][1]=50 #浅copy可以用来创建联合账号,共同存款的变化,但实际上不会这样用。 print(p1)
print(p2)

test.py

元组不能更改,可理解为只读列表。两种方法:count、index

 names=(("alex","jack"),(1,2),(8,9),(1,2),[6,7])
print(names.index((8,9))) #查询位置
print(names.count((1,2))) #出现次数

tuple

程序:购物车程序

需求:

  1. 启动程序后,让用户输入工资,然后打印商品列表
  2. 允许用户根据商品编号购买商品
  3. 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
  4. 可随时退出,退出时,打印已购买商品和余额
     '''shoplist=[[1,"Iphone",5800],[2,"Macbook",12000],[3,"Surfacelaptop",8888],[4,"Bike",800],[5,"Coffe",30]]
    salary=int(input("Enter integer salary of you:")) for i in shoplist:
    print(i)
    buy=input("Choose something you like and enter the serial number:")
    if buy==1:
    if salary>shoplist[0][3]:
    salary=salary-shoplist[0][3]
    print("You have chosen the",shoplist[0][2])
    else:
    print("Your balance is not enough")
    elif buy==2:
    if salary>shoplist[1][3]:
    salary=salary-shoplist[1][3]
    print("You have chosen the",shoplist[1][3])
    else:
    print("Your balance is not enough")'''
    #以上为自己编写的错误的思路 product_list=[("Iphone",5800),
    ("Mac Pro",9800),
    ("Bike",800),
    ("Watch",10600),
    ("Coffee",31),
    ("Alex Python",120)]
    shopping_list=[]
    while True:
    salary=input("Input your salary:")
    if salary.isdigit(): #判断是不是数字
    salary=int(salary)
    while True:
    for index,item in enumerate(product_list): #enumerate把列表下标直接取出来
    #print(product_list.index(item),item)
    print(index+1,".",item,sep="")
    user_choice=input('''Choose something you like and enter the serial number (You can press "q "to quit)>>>:''')
    if user_choice.isdigit():
    user_choice=int(user_choice)
    if user_choice<=len(product_list) and user_choice>=1:
    p_item=product_list[user_choice-1]
    if p_item[1]<=salary:#买得起
    shopping_list.append(p_item)
    salary -=p_item[1]
    print("Added %s into shopping cart,your current balance is \033[31;1m%s\033[0m"%(p_item,salary)) #\033[31;1m...\033[0m 加颜色
    else:
    print("\033[31;1m你的余额只剩 %s 啦,还买个毛线!\033[0m"%salary)
    else:
    print("product code [%s] is not exist!"%user_choice)
    elif user_choice=="q":
    print("------shopping list------")
    for p in shopping_list:
    print(p)
    print("Your current balane:",salary,"\nThank for your shopping and looking forward to your next visit!")
    exit()
    else:
    print("Invalid option")
    else:
    print("Please enter an integer")

    shoplist_

     product_list=[["Iphone",5800],["MacBook",8000],["Surfacelaptop",9999],["Iwatch",10000],["ThinkPad",12000]]
    shoplist=[]
    while True:
    salary = input("Enter your salary:")
    if salary.isdigit():
    salary=int(salary)
    while True:
    for item in product_list:
    print(product_list.index(item)+1,".",item,sep="")
    users_choice=input("Choose something you like\nEnter the sequence number to buy"
    "(You can press the 'q' to quit) --->:")
    if users_choice.isdigit():
    users_choice = int(users_choice)
    if users_choice<=len(product_list) and users_choice>=1:
    if product_list[users_choice-1][1]<=salary:
    shoplist.append(product_list[users_choice-1])
    salary=salary-product_list[users_choice-1][1]
    print("Your current balance:",salary)
    else:
    print("你的钱只剩%s了,还买个毛线!"%salary)
    exit()
    else:
    print("Invalid option")
    elif users_choice == "q":
    print("------shoplist------")
    for i in shoplist:
    print(i)
    print("Your curren balance:%s"%salary)
    print("Looking forward your next shopping!")
    exit()
    else:
    print("Invalid option")
    else:
    print("Please enter an integer!")

    shoplist_by_self

二、字符串操作

特性:不可修改 

 name="my\tname is {name} and i am {year} years old"
print(name.capitalize())#首字母大写
print(name.count("a"))#统计字母出现次数
print(name.center(50,"-")) #居中
print(name.endswith("ang")) #判断字符串是不是以..结尾
print(name.expandtabs(tabsize=30)) #\t 加空格
print(name[name.find("name"):]) #find找字符串位置,字符串也可以切片,用法与列表一样
print(name.format(name="jyh",year=24))
print(name.format_map({"name":"jyh","year":24})) #字典
print("ab23".isalnum()) #阿拉伯的数字和字符
print("ac".isalpha()) #纯英文字符
print("1A".isdecimal()) #判断十进制,没什么用
print("1A".isdigit()) #判断整数
print("A1".isidentifier())#判断是不是一个合法的标识符
print("a1".islower())#判断小写
print("1/3".isnumeric())#判断整数,没什么用
print(" ".isspace())#判断空格
print(" My Name Is ".istitle())#判断每个首字母是否大写
print(" My Name Is ".isprintable())#判断是否可以打印,用的很少 tty file,drive file
print(" My Name Is ".isupper())#判断大写
print("+".join(["","",""])) #连接字符串,经常用
print(name.ljust(50,"*")) #长度50,不够在后面用*补
print(name.rjust(50,"-")) #长度50,不够在前面用-补
print("Alex".lower()) #大写变小写
print("Alex".upper()) #小写变大写
print("\n Alex".lstrip()) #从左去掉空格后回车,rstrip同理,strip用得最多 p=str.maketrans("abcdef",'') #类似数字对应,必须一样多
print("alex li".translate(p)) #用的不多 print("alex li".replace("l","L",1)) #替换
print("alex lil".rfind("l")) #从左往右,找到最后面值的下标
print("alex lil".split("l")) #按分隔符"l"将字符串分成列表
print("1+2+3+4".split("+")) #按分隔符"+"将字符串分成列表
print("1+2\n+3+4".splitlines()) #按换行符(识别不同系统的换行符)将字符串分成列表
print("Alex Li".swapcase()) #大小写互换
print("AleX Li".title()) #首字母变大写
print("AleX Li".zfill(50)) #没什么用

str

三、字典操作

字典一种key - value(键-值) 的数据类型,使用就像我们上学用的字典,通过笔划、字母来查对应页的详细内容。

字典的特性:

  • dict是无序的
  • key必须是唯一的,so 天生去重
     #key-value 键-值
    info = {
    'stu1101': "A",
    'stu1102': "B",
    'stu1103': "C",
    } print(info) #字典是无序的
    print(info["stu1101"]) #取值,查找
    info["stu1101"]="D" #改
    info["stu1104"]="E" #创建
    #del info["stu1101"]
    #info.pop("stu1101")
    #info.popitem() #随机删,别用,无意义
    print(info) print(info["stu1101"]) #查找,没有的话出错
    print(info.get("stu1105"))#查找,没有的话打印None
    print("stu1107" in info) #查找,没有的话打印False #info.has_key("1107") in python2.x b={"stu1101":"Alex",1:3,2:5}
    info.update(b) # 有交叉的key覆盖,没有的话创建
    print(info) print(info.items()) #把字典转成列表 c=dict.fromkeys([6,7,8],[1,{"name":"alex"},444]) #初始化一个新的字典
    print(c)
    c[7][1]["name"]="Jack Chen"
    print(c) # 三个Key共享一个内存地址,也就是都会变成"Jack Chen" for i in info:
    print(i,info[i]) for k,v in info.items():
    print(k,v) #有一个将字典转化成列表的过程,速度慢

    dictionary_

     av_catalog = {
    "A":{
    "A1": ["A11","A12"],
    "A2": ["A21","A22"],
    "A3": ["A31","A32"],
    "A4":["A41","A42"]
    },
    "B":{
    "B1":["B11","B12"]
    },
    "C":{
    "C1":["C11","C12"]
    }
    } av_catalog["C"]["C1"][1]="C13"
    print(av_catalog)
    av_catalog.setdefault("C",{"C11":[1,2]})
    print(av_catalog)
    av_catalog.setdefault("D",{"C11":[1,2]}) #先到字典去key,取到返回,取不到,重新加一个
    print(av_catalog)

    dictionary2

程序练习

程序: 三级菜单

要求:

  1. 打印省、市、县三级菜单
  2. 可返回上一级
  3. 可随时退出程序
     data={
    '北京':{
    "昌平":{
    "沙河":["oldboy","test"],
    "天通苑":["链家地产","我爱我家"],
    },
    "朝阳":{
    "望京":{"奔驰","陌陌"},
    "国贸":{"CICC","HP"},
    "东直门":{"Advent","飞信"},
    },
    "海淀":{},
    },
    '山东':{
    "德州":{},
    "青岛":{},
    "济南":{},
    },
    '广东':{
    "东莞":{},
    "常熟":{},
    "佛山":{},
    },
    }
    exit_flag=False
    while not exit_flag:
    for i in data:
    print(i)
    choice=input("选择进入1>>>:")
    if choice in data:
    while not exit_flag:
    for i2 in data[choice]:
    print("\t",i2) #\t为了区分级别加空格
    choice2 = input("选择进入2>>>:")
    if choice2 in data[choice]:
    while not exit_flag:
    for i3 in data[choice][choice2]:
    print("\t\t", i3)
    choice3 = input("选择进入3>>>:")
    if choice3 in data[choice][choice2]:
    for i4 in data[choice][choice2][choice3]:
    print("\t\t\t",i4)
    choice4 = input("最后一层,按b返回>>")
    if choice4=="b":
    pass #占位符,否则报错
    elif choice4=="q":
    exit_flag=True
    if choice3 == "b":
    break
    elif choice3 == "q":
    exit_flag = True
    if choice2 == "b":
    break
    elif choice2 == "q":
    exit_flag = True
    elif choice == "q":
    exit_flag = True

    three_level_menu

四、集合

集合是一个无序的,不重复的数据组合,它的主要作用如下:

  • 去重,把一个列表变成集合,就自动去重了
  • 关系测试,测试两组数据之前的交集、差集、并集,子集,对称差集等关系

(学Python和学Linux的人可能重复,统计报名人数时需要去重(去重)。混在一块之后把两个班都报了的人再分出来,取列表中的交集(关系测试)。)

 list_1=[1,4,5,7,3,6,7,9]
list_1=set(list_1) #转换为集合,自动去重,集合也是无序的
print(list_1,type(list_1)) list_2=set([2,6,0,66,22,8,4])
print(list_2,type(list_2))
print("-----------")
print(list_1.intersection((list_2))) #取交集
print(list_1&list_2)
print("-----------")
print(list_1.union(list_2)) #取并集
print(list_1|list_2)
print("-----------")
print(list_1.difference(list_2)) #取差集,取1里有2里没有的
print(list_1-list_2)
print(list_2.difference(list_1)) #取差集,取2里有1里没有的
print(list_2-list_1)
print("-----------")
print(list_1.issubset(list_2)) #判断是否为子集
print(list_1.issuperset(list_2)) #判断是否为父集
list_3=set([1,3,7])
print(list_3.issubset(list_1))
print(list_1.issuperset(list_3))
print("-----------")
print(list_1.symmetric_difference(list_2)) #对称差集,去掉两个的交集
print(list_1^list_2)
print("-----------")
print(list_2.isdisjoint(list_3)) #没有交集返回为True
print("-----------------------")
list_1.add(999)
print(list_1) #添加一项
list_1.update([888,777,555])
print(list_1) #添加多项
print("-----------")
list_1.remove(999)
print(list_1) #删除一项,该元素不存在的话会报错
# print(list_1.pop()) #任意删除一项
list_1.discard(3232)
print(list_1) #指定删除,该元素不存在不会报错,但remove会报错

set_

五、文件操作

对文件操作流程

  1. 打开文件,得到文件句柄并赋值给一个变量
  2. 通过句柄对文件进行操作
  3. 关闭文件
 # data=open("yesterday",encoding="utf-8").read() # 打开文件,但不能修改

 '''d=open("yesterday","r",encoding="utf-8") #文件句柄(文件内存对象),可操作
data=d.read()
data2=d.read()
print(data)
print("---------data2-----------",data2) #执行第二遍,从上次结束的地方继续读,所以data2后面没东西了,类似光标'''
'''f=open("yesterday2","w",encoding="utf-8") #创建一个文件,可以写,但覆盖之前的文件,以前的内容没了
f.write("我爱北京*,\n")
f.write("*上太阳升")''' '''f=open("yesterday2","a",encoding="utf-8") # a 追加,
f.write("\n我爱北京*....\n")
f.write("*上太阳升....")''' '''f=open("yesterday2","a",encoding="utf-8")
f.write("\nwhen i was young i listen to the radio\n") #a追加,不覆盖原来的文件,也不可读
data=f.read()
print("---read",data)''' '''f=open("yesterday","r",encoding="utf-8")
print(f.readline())
print(f.readline())
print(f.readline()) #读前三行,但写代码尽量避免重复的代码'''
'''f=open("yesterday","r",encoding="utf-8")
for i in range(3):
print(f.readline().strip())'''
#f.readlines #列表
'''f=open("yesterday","r",encoding="utf-8")
for line in f.readlines():
print(line.strip())''' '''f=open("yesterday","r",encoding="utf-8")
for index,line in enumerate(f.readlines()): #f.readlines()只适合读小文件,大文件费时间
if index ==9:
print("----我是分割线----")
continue
print(line.strip())''' #low loop
'''#high bige
count=0
f=open("yesterday","r",encoding="utf-8")
for line in f: # f变为了迭代器
if count==9:
print("----我是分割线----")
count += 1
continue
print(line.strip()) #打印一行,内存中删除一行,不占内存
count += 1
'''
'''f=open("yesterday","r",encoding="utf-8")
print(f.tell()) #打印当前位置
print(f.readline())
print(f.tell())
f.seek(10) #回到的位置
print(f.readline()) print(f.encoding) #打印文件的编码 print(f.fileno()) #返回内存中的编号(不是地址)与操作系统有关。不常用 print(f.flush()) # 强制刷新,不存到缓存'''
'''f=open("yesterday","r",encoding="utf-8")
print(f.truncate())# 不写就是清空,写数字就是从开头截断多少个字符,移动光标seek也是从开头截断''' '''f=open("yesterday","r+",encoding="utf-8") #读写,可用
print(f.readline())
print(f.readline())
print(f.readline())
f.write("----w----") #写到最后了
print(f.readline())''' '''f=open("yesterday2","w+",encoding="utf-8") #写读,没什么卵用
f.write("----w----\n")
f.write("----w----\n")
f.write("----w----\n")
f.write("----w----\n")
print(f.tell())
f.seek(11)
print(f.tell())
print(f.readline())
f.write("secondline") #还是追加到后面了''' # f=open("yesterday","a+",encoding="utf-8") #追加读写,也是加在后面 '''f=open("yesterday2","rb") # 二进制文件
print(f.readline())
print(f.readline()) # 网络传输(socket.py)只能用二进制格式传输 in Python3.x
# 下载的(视频等)文件,以字符的格式打开可能造成文件损坏''' '''f=open("yesterday2","wb")
f.write("hello binary".encode("utf-8"))'''

file_op

 f=open("yesterday","r",encoding="utf-8")
f_new=open("yesterday.bak","w",encoding="utf-8") for line in f:
if "肆意的快乐等我享受"in line:
line=line.replace("肆意的快乐等我享受","肆意的快乐等jyh享受")
f_new.write(line)
f.close()
f_new.close() f=open("yesterday","r",encoding="utf-8")
f_new=open("yesterday.bak","w",encoding="utf-8")
'''
import sys
find_str=sys.argv[1]
replace_str=sys.argv[2]
for line in f:
if find_str in line:
line=line.replace(find_str,replace_str)
f_new.write(line)
f.close()
f_new.close()
''' # 传参数替换

file_modify

刷新(进度条)

 import sys,time
for i in range(20):
sys.stdout.write("#") #不换行打印
sys.stdout.flush()
time.sleep(0.2)

jindutiao

程序练习  

程序1: 实现简单的shell sed替换功能

程序2:修改haproxy配置文件 

with语句

为了避免打开文件后忘记关闭,可以通过管理上下文,即:

 f=open("yesterday","r",encoding="utf-8")
with open("yesterday","r",encoding="utf-8") as f:
for line in f:
print(line) #自动关闭文件

with_

在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:

 f=open("yesterday","r",encoding="utf-8")
f2=open("yesterday2","r",encoding="utf-8")
with open("yesterday","r",encoding="utf-8") as f,\
open("yesterday2","r",encoding="utf-8") as f2: #一行不超过80个字符
for line in f:
print(line) #自动关闭文件

multiple

如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

六、字符编码与转码

 import sys
print(sys.getdefaultencoding()) #Python默认编码

defaultencoding_

详细文章:

http://www.cnblogs.com/yuanchenqi/articles/5956943.html

http://www.diveintopython3.net/strings.html

需知:

1.在python2默认编码是ASCII, python3里默认是unicode

2.unicode 分为 utf-32(占4个字节),utf-16(占两个字节),utf-8(占1-4个字节), so utf-16就是现在最常用的unicode版本, 不过在文件里存的还是utf-8,因为utf8省空间

3.在py3中encode,在转码的同时还会把string 变成bytes类型,decode在解码的同时还会把bytes变回string

 s="你好"
s_gbk=s.encode("gbk") #除了改编码集,还要变成bytes类型
print(s_gbk)
print(s.encode()) gbk_to_utf8=s_gbk.decode("gbk").encode("utf-8") #decode告诉Unicode你是gbk,encode转成utf-8
print("utf8",gbk_to_utf8)

encode_

 # -*-coding:gbk-*- #文件是gbk编码
# Author:JYH s="你好" #这里还是unicode(默认的)编码
print(s.encode("gbk")) #显示的是gbk的编码格式
print(s.encode("utf-8" ))
print(s.encode("gb2312").decode("gbk"))

encode2

Python学习笔记_week2_列表、元组、字典、字符串、文件、i编码

上图仅适用于py2