Python学习【2】

来源:互联网 发布:淘宝客服个人简历模板 编辑:程序博客网 时间:2024/06/16 19:35

sys模块

>>> import sys>>> print(sys.path)['', 'C:\\Users\\heimu\\AppData\\Local\\Programs\\Python\\Python35\\Lib\\idlelib', 'C:\\Users\\heimu\\AppData\\Local\\Programs\\Python\\Python35\\python35.zip', 'C:\\Users\\heimu\\AppData\\Local\\Programs\\Python\\Python35\\DLLs', 'C:\\Users\\heimu\\AppData\\Local\\Programs\\Python\\Python35\\lib', 'C:\\Users\\heimu\\AppData\\Local\\Programs\\Python\\Python35', 'C:\\Users\\heimu\\AppData\\Local\\Programs\\Python\\Python35\\lib\\site-packages']Python库的寻找路径(python环境变量)

注意:文件名不要和模块名重复,一般安装的第三方库会自动装在site-packages路径下,自带的库一般放在lib路径下(前一级)

import sysprint(sys.argv)

打印当前文件的路径,还可以获取传递的参数,打印参数

os模块

跟系统进行交互的模块

import osos.system("dir")#执行命令,打印,不保存

关于.pyc文件

compile(编译),python其实也是一门先预编译后解释的语言,预编译之后成为字节码文件

数据类型

python3中long int 和 int 均为 int

三元运算:

result = 值1 if 条件 else 值2

Python3对文本和二进制数据坐了清晰的区分,文本总是Unicode,由str类型,二进制数据(视频,音频)bytes类型,二者不可混用

str<——>bytes,utf-8<—>二进制

>>> name = '黑木'>>> print(name)黑木>>> name.encode()b'\xe9\xbb\x91\xe6\x9c\xa8'>>> name.encode(encoding="utf-8")b'\xe9\xbb\x91\xe6\x9c\xa8'>>> name.encode(encoding="utf-8").decode()'黑木'>>> name.encode(encoding="utf-8").decode(encoding="utf-8")'黑木'>>> 

列表

>>> name = ["kobe","wade","durant","curry"]#定义列表>>> name[0]#通过下标访问元素,从0开始'kobe'>>> name[-1]#-1代表从右边开始'curry'

切片

>>> name[1:3]['wade', 'durant']>>> name[1:3]#包含1不包含3,顾头不顾尾['wade', 'durant']>>> name[:3]#相当于0-3,0可以忽略['kobe', 'wade', 'durant']>>> name[1:-1]#下标从1到-1,不包括-1['wade', 'durant']>>> name[1:]#包含最后一个元素['wade', 'durant', 'curry']>>> name[::2]#2代表步长,隔一个取['kobe', 'durant']

增 append

>>> name.append('heimu')#追加到最后>>> print(name)['kobe', 'wade', 'durant', 'curry', 'heimu']

插 insert

>>> name.insert(1,'jordan')#插入到指定位置>>> print(name)['kobe', 'jordan', 'wade', 'durant', 'curry', 'heimu']

更改

>>> name[1] = 'heimu'#直接赋值修改>>> print(name)['kobe', 'heimu', 'wade', 'durant', 'curry', 'heimu']

>>> del name[1]>>> name['kobe', 'wade', 'durant', 'curry', 'heimu']>>> name.remove("heimu")#删除指定元素>>> name['kobe', 'wade', 'durant', 'curry']>>> name.pop()#默认弹出最后一个元素'curry'>>> name['kobe', 'wade', 'durant']>>> name.pop(1)#指定弹出元素'wade'>>> name['kobe', 'durant']

查找索引:name.index(‘aaa’’)
统计个数:name.count(‘aaa’’)
清除:name.clear()
反转:name.reverse()
排序:name.sort()默认按照ASCII顺序从低到高
扩展:name.extend(name_1)将name_1添加到name后面
del name_1 删除整个列表


name_2 = name.copy() 浅copy,只copy第一层,其实本质上是内存地址··
深copy
import copy
name_2 = copy.deepcopy(name)完全克隆


浅copy,创建联合账号
import copy
person = [‘name’,[‘a’,100]]
p1 = copy.copy(person)
p2 = person[:]
p3 = list(person)


tuple元组() 只读列表

不可修改的列表
只有两个方法 count,index

例子:购物车程序

#!/usr/bin/env python# -*- coding:utf-8 -*-# Author: Heimuprotoduct_list = [    ('Apple iphone8',5800),    ('Apple iphone8Plus',6688),    ('Apple iphoneX',8788),    ('Apple iPad Pro',4388),    ('Apple Watch Sport',2488),    ('Apple MacBook',12788)]Salary = input('Please input your salary: ')Shoping_list = []product_price = []if Salary.isdigit():    Salary = int(Salary)    while True:        # for item in protoduct_list:        #   print(protoduct_list.index(item),item)        for index,item in enumerate(protoduct_list):            product_price.append(item[1])            print(index,item)        lowest_price = min(product_price)        if Salary >= lowest_price:            user_choice = input('please input the serial number of the products you want to buy: ')            if user_choice.isdigit():                user_choice = int(user_choice)                if user_choice>=0 and user_choice<len(protoduct_list):                    buy_item = protoduct_list[user_choice]                    if buy_item[1]<=Salary:                        Salary -= buy_item[1]                        Shoping_list.append(buy_item)                        print('your balance is \033[31;1m%s\033[0m' % Salary)                    else:                        print('your balance is not enough')                else:                    print('please input the number between \033[31;1m0\033[0m and \033[31;1m%s\033[0m'% (len(protoduct_list)-1))                print()            elif user_choice == 'q':                print('---------------Your Shopping List----------------')                for item in Shoping_list:                    print(item)                print('your balance is \033[31;1m%s\033[0m'% Salary)                exit()            else:                print('Invalid Input')        else:            print("Oh!\033[31;1myour are so poor\033[0m and you can't afford to buy any of the products.")            print("Work hard and earn enough money to buy things again!!!")            exit()else:    print('Invalid Input')

enumerate用法

>>> a = [1,2,3]>>> for i in enumerate(a):print(i)(0, 1)(1, 2)(2, 3)

字符串用法


str.capitalize()首字母大写
str.count(‘a’)str中a的个数
str.center(50,”-”)50个字符str放中间,不够的-补足
str.endwith(“a”)判断以什么结尾
str.find(‘a’)返回第一次找到的字符的索引
字符串也可以切片,和list一样
str.format()用于格式化输出
str.format_map({‘name’:’alex’})字典,格式化
str.isalnum()字母和数字
str.isalpha()英文
str.isdecimal()十进制
str.isdigit()整数
str.isidentifier()判断是不是一个合法的标示符(合法的变量名)
str.islower()小写
str.isnumeric()和isdigit差不多
str.isspace()空格
str.istitle() 每个字母的首字母大写
str.isprintable()可打印的, tty file,drive file
str.isupper()大写
print(‘+’.join([‘1’.’2’,’3’]))
name.ljust(50,*)长度50,不够补足
name.rjust(50,*)长度50,不够补足
name.lower()大写变小写
name.upper()小写变大写
name.lstrip()去除左边的空格或者换行
name.rstrip()去除右边
name.strip()两边都去


p = str.maketrans(‘abcdef’,’123456’)
print(‘heimu’.translate(p))
str.replace(‘a’,’A’,1)
str.rfind(‘a’)找到的最右边的值的下标
‘1+2+3’.split(‘+’)分解字符串,默认空格为分隔符
str.splitlines()按照换行分解
str.swapcase()大写变小写,小写变大写
str.title()每个字符的首字母大写
str.zfill(50)补位0


字典 key-value类型{}

无序,key是唯一的,所以无重复
查,修改,创建。。。直接
删除 del info[“stu1101”]
info.pop(“stu1101”)
info.popitem()随便删


查找
info.get(‘stu1103’)有就返回,么有不报错
判断一个key在不在字典
print(‘stu1103’ in info)


info.value()
info.key()
info.setdefault()如果key存在,直接返回old,否则创建新的值


info.update(b)字典合并,相同的键值覆盖
info.item()字典转列表


dict.fromkeys([6,7,8],”test”)初始化一个字典,本质上一个key共享一个内存,类似浅层copy
for i in info:
print(i)
循环键值,高效,推荐

for k,v in info.items():
print(k,v)

例子:
三级菜单

原创粉丝点击