Python进阶

Python进阶

成员资格:

>>> user_name = ["DemoD_","DemoLi"]
		 
>>> input("Enter you user name:") in user_name
		 
Enter you user name:DemoD_
True

join:

“str”.join(“object”) : 将str作为分隔符添加到object每个元素之间

列表可以修改,而元组不可以修改

List

1.del:

>>> a = [1, 2, 3, 4]
		 
>>> del a[1]
		 
>>> a
		 
[1, 3, 4]

2.append:
将一个对象加到列表末尾

>>> a = [1, 2, 3, 4]
		 
>>> a.append(5)
		 
>>> a
		 
[1, 2, 3, 4, 5]

3.clear:
清空列表

>>> a.clear()
		 
>>> a
		 
[]

4.copy:
复制列表

>>> a = [1, 2, 3, 4]
		 
>>> b = a.copy()
		 
>>> b
		 
[1, 2, 3, 4]

5.count:
计算元素在列表中出现的个数

>>> a = [1, 2, 3, 2, 3, 4, 2]
		 
>>> a
		 
[1, 2, 3, 2, 3, 4, 2]
>>> a.count(2)
		 
3

6.extend:
可以将多个元素添加到列表尾部,类似拼接,返回列表,可以用来拼接列表

>>> a = [1, 2, 3]
		 
>>> b = [4, 5, 6]
		 
>>> a.extend(b)
		 
>>> a
		 
[1, 2, 3, 4, 5, 6]

7.index:
返回指定元素的下标

>>> str = ['a', 'b', 'c', 'd']
		 
>>> str.index('a')
		 
0
>>> str.index('b')
		 
1

8.insert:
将一个对象插入列表

>>> str = ['a', 'b', 'c', 'd']
>>>> str.insert(2, 'e')
>>> str
		 
['a', 'b', 'e', 'c', 'd']

9.pop:
删除列表中最后一个元素,并返回删除元素,也可以指定位置删除元素

>>> str
		 
['a', 'b', 'e', 'c', 'd']
>>> str.pop()
		 
'd'
>>> str.pop(0)
		 
'a'
>>> str
		 
['b', 'e', 'c']

10.remove:
删除指定元素在列表中第一个元素

>>> str = ['a', 'b', 'c', 'd']
		 
>>> str.remove('a')
		 
>>> str
		 
['b', 'c', 'd']

11.reverse:
将列表元素颠倒

>>> str = ['a', 'b', 'c']

>>> str.reverse()
		 
>>> str
		 
['c', 'b', 'a']

12.sort:
将列表的元素从小到大排列

>>> a = [3, 2, 5, 0, 1]
>>> a.sort()
		 
>>> a
		 
[0, 1, 2, 3, 5]

notice
enumerate

>>> li = ["a", "b", "c"]
>>> for i,v in enumerate(li):
	print(i,v)

	
0 a
1 b
2 c
>>> for i,v in enumerate(li,1):
	print(i,v)

	
1 a
2 b
3 c
>>> 

元组(tuple)

一个元素的元组表示

(58,)

元组的初始化

>>> a = [1, 2, 3]
		 
>>> b = tuple(a)
		 
>>> b
		 
(1, 2, 3)

元组和列表相似很多方法都可以用

字符串(不可变)

1.替换字段名:

>>> a = "{fear}{}{foo}{}".format(1, 2, fear = 3, foo = 4)
		 
>>> a
		 
'3142'
>>> a = "{0}{2}{1}".format("DemoD_","DemoLi_", "DemoFu_")
		 
>>> a
		 
'DemoD_DemoFu_DemoLi_'
>>> a = "Hello %s!" %("World")
		 
>>> a
		 
'Hello World!'

2.宽度,精度,千位分隔符:

>>> # 设置宽度
>>> a = "{name:10}".format(name = "DemoD_")
		 
>>> a
		 
'DemoD_    '
>>> a = "{:10}".format("DemoD")
		 
>>> a
		 
'DemoD     '
>>>  # 设置精度
>>> a = "PI equal {:.2f}".format(math.pi)
		 
>>> a
		 
'PI equal 3.14'
>>> # 设置千位分隔符
		 
>>> a ="{:,}".format(10**100)
		 
>>> a
		 
'10,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000'

3.符号,对齐方式,填充:

在宽度,精度前添加符号作为填充符

>>> a = "{:010.2f}".format(math.pi)
		 
>>> a
		 
'0000003.14'

对齐方式向左 , 居中 , 向右对齐。< , ^ , >

>>> a = "{0:<10.2f}\n{0:^10.2f}\n{0:>10.2f}\n".format(math.pi)
		 
>>> print(a)
		 
3.14      
   3.14   
      3.14

4.字符串方法:
(1)center:
将字符居中显示

>>> a = "Who are you?".center(20,'*')
		 
>>> a
		 
'****Who are you?****'

(2)find:
查找指定元素,返回下标,不存在返回-1

>>> a = "Life is short, you need python"
		 
>>> a.find("python")
		 
24
>>> a.find("h",10,-1)
		 
27

(3).join:
与split相反

>>> a = [1, 2, 3, 4, 5]

>>> " ".join(a)
		 
Traceback (most recent call last):
  File "<pyshell#89>", line 1, in <module>
    " ".join(a)
TypeError: sequence item 0: expected str instance, int found
>>> a = ['1', '2', '3', '4']
		 
>>> "".join(a)
		 
'1234'

说明列表的元素为字符串才能应用
(4).lower
对应的有upper
返回字符串的小写

>>> a = "Hello World!"
		 
>>> a.lower()
		 
'hello world!'

(5)title
词首大写

>>> a = "hello world!"
		 
>>> a.title()
		 
'Hello World!'

(6)replace:
用另一个字符串代替原字符串中的某段字符串

>>> a = "I love python".replace("python", "DemoLi_")
		 
>>> print(a)
		 
I love DemoLi_

(7).split:
将字符串拆分为序列

>>> a = "D://PythonDemo//MySomeTest//chinamap.jpg"
		 
>>> a.split("/")
		 
['D:', '', 'PythonDemo', '', 'MySomeTest', '', 'chinamap.jpg']

(8)strip:
删除字符串开头结尾的空格,或者指定字符

>>> a = "    Life is short, you need python    "
		 
>>> a.strip()
		 
'Life is short, you need python'
>>> a = "***Life is short, you need python***"
		 
>>> a.strip("*")
		 
'Life is short, you need python'

字典(key - value)

>>> person = [("name","DemoD_"),["age","22"]]
>>> dict_person = dict(person)
>>> dict_person
{'name': 'DemoD_', 'age': '22'}
>>> dict_person["name"]
'DemoD_'
>>> dict_person["age"]
‘22’

1.字典的基本操作

>>> len(dict_person)  # 返回字典中键值对的个数
2
>>> dict_person["name"]  # 返回key对应的value
'DemoD_'
>>> dict_person["name"] = "DemoLi_"    # 修改或添加元素
>>> dict_person
{'name': 'DemoLi_', 'age': '22'}
>>> del dict_person["name"]   # 删除指定键值对
>>> dict_person
{'age': '22'}
>>> "age" in dict_person  # 判断键值对是否存在字典中
True

A simple example

>>> home = {
	"DemoD_":{
		"phone":"111",
		"addr":"aaa"
		},
	"DemoLi_":{
		"phone":"222",
		"addr":"bbb"
		},
	"DemoFu":{
		"phone":"333",
		"addr":"ccc"
		}
	}
>>> labels = {
	"phone":"phone number",
	"addr":"address"
	}
>>> name = input("Name:")
Name:DemoD_
>>> requests = input("Phone number(p) or address(a)?")
Phone number(p) or address(a)?p
>>> if requests =="p":
	key = "phone"

	
>>> if requests =="a":
	key = "addr"

	
>>> if name in home:
	print("{}'s {} is {}.".format(name,labels[key],home[name][key]))

	
DemoD_'s phone number is 111.

字典方法

1.clear:
清空字典
(1).如果你想保存一个字典,在清空,不想清空保存字典的数据。

>>> x = {}
>>> y = x
>>> x["key"] = "value"
>>> x = {}
>>> x
{}
>>> y
{'key': 'value'}

(2).你想清空数组,同时想将同步的字典也清空。

>>> x = {}
>>> y = x
>>> x["key"] = "value"
>>> y
{'key': 'value'}
>>> x.clear()
>>> x
{}
>>> y
{}

2.copy:
复制

>>> computer = {"user_name":"admin","machines":["lenovo","inter_i5", "window_10"]}
>>> computer_copy = computer.copy()
>>> computer_copy["user_name"] = "DemoD_"  # 副本替换值,原本无影响
>>> computer_copy["machines"].remove("window_10")  # 副本修改,原本做相应的变换
>>> computer_copy
{'user_name': 'DemoD_', 'machines': ['lenovo', 'inter_i5']}
>>> computer
{'user_name': 'admin', 'machines': ['lenovo', 'inter_i5']}

原件修改
deepcopy

>>> d = {}
>>> d["name"] = ["DemoD_","DemoLi_"]
>>> c = d.copy()
>>> c
{'name': ['DemoD_', 'DemoLi_']}
>>> dc = deepcopy(d)
>>> dc
{'name': ['DemoD_', 'DemoLi_']}
>>> d["name"].append("DemoFu_")
>>> c
{'name': ['DemoD_', 'DemoLi_', 'DemoFu_']}
>>> dc
{'name': ['DemoD_', 'DemoLi_']}

3.fromkeys:
创建指定key,key的value都为None

>>> a = {}.fromkeys(["name","age"])
>>> a
{'name': None, 'age': None}

也可以这样

>>> a = {}.fromkeys(["name","age"],"unknown")
>>> a
{'name': 'unknown', 'age': 'unknown'}

4.get:
通过key查找value

>>> d = {}
>>> print(d["name"])  # 					不存在的这样会报错
Traceback (most recent call last):
  File "<pyshell#96>", line 1, in <module>
    print(d["name"])
KeyError: 'name'
>>> print(d.get("name"))		#							get就不会报错
None
>>> d.get("name","not_exist")  #					如果不存在,可以设置返回值
'not_exist'
>>> d["name"]="DemoD_"
>>> d["name"]
'DemoD_'
>>> d.get("name")
'DemoD_'

5.items:
返回字典中所有的键值对

>>> d = {"title":"BaiDu","url":"http://www.baidu.com","spam":0}
>>> d.items()
dict_items([('title', 'BaiDu'), ('url', 'http://www.baidu.com'), ('spam', 0)])
>>> len(d)
3

6.keys 和 value:

>>> d.keys()
dict_keys(['title', 'url', 'spam'])
>>> d.values()
dict_values(['BaiDu', 'http://www.baidu.com', 0])

7.pop:
删除指定键值并返回value

>>> d = {"x":1,"y":2}
>>> d.pop("x")
1
>>> d
{'y': 2}

8.popitem:
删除最后一个键值,返回value;因为字典是无序,好处就是删除不用知道key

>>> d = {"x":1,"y":2,"z":3}
>>> d.popitem()
('z', 3)
>>> d
{'x': 1, 'y': 2}

9.setdefault:
返回索引的value若不存在则新建,并返回设置的value

>>> d = {}
>>> d.setdefault("name","not_exist")
'not_exist'
>>> d
{'name': 'not_exist'}
>>> d["name"] = "DemoD_"
>>> d.setdefault("name","not_exist")
'DemoD_'

10.update:

>>> d = {
	"title":"Python",
	"price":100,
	"version":3.8
	}
>>> x = {"title":"Life is short ,you need python"}
>>> d.update(x)
>>> d
{'title': 'Life is short ,you need python', 'price': 100, 'version': 3.8}

print:

print自动换行,设置print不自动换行

print("Hello World!",end="")

eval

>>> s = input("please enter a integer")
please enter a integer1
>>> s
'1'
>>> s = eval(input("please enter a integer"))
please enter a integer1
>>> s
1

repr:

将指定的object转换为string

>>> repr("x")
"'x'"

class Person:
    def set_name(self, name):
        self.name = name

    def get_name(self):
        return self.name

    def greet(self):
        print("Hello, world! I'm {}".format(self.name))


foo = Person()
bar = Person()
foo.set_name("DemoD_")
bar.set_name("DemoLi_")
foo.greet()
bar.greet()

继承

class A:
    def hello(self):
        print("Hello, I'm A")


class B(A):
    def hello(self):
        print("Hello, I'm B")


a = A()
b = B()
print(a.hello())
print(b.hello())

模块

# hello.py
def hello():
	print("Hello World!")
	
>>>import hello
>>>hello.hello()
Hello World!

Time

>>> import time
>>> t = time.time()
>>> print("当前时间", t)
当前时间 1537961526.6770139
>>> #时间戳
>>> import time
>>> localtime = time.localtime(time.time())
>>> print("当前时间:",localtime)
当前时间: time.struct_time(tm_year=2018, tm_mon=9, tm_mday=26, tm_hour=19, tm_min=33, tm_sec=3, tm_wday=2, tm_yday=269, tm_isdst=0)
>>> import time
>>> localtime = time.asctime(time.localtime(time.time()))
>>> print("当前时间:",localtime)
当前时间: Wed Sep 26 19:33:51 2018

process

>>> import subprocess
>>> res =subprocess.Popen("dir", shell = True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
>>> print(res.stdout.read().decode("gbk"))
 驱动器 D 中的卷是 软件

 卷的序列号是 000C-6CCC



 D:\python3 的目录



2018/08/21  14:51    <DIR>          .

2018/08/21  14:51    <DIR>          ..

2018/07/26  11:10    <DIR>          DLLs

2018/07/26  11:09    <DIR>          Doc

2018/08/16  11:25    <DIR>          include

2018/08/11  15:06    <DIR>          Lib

2018/07/26  11:09    <DIR>          libs

2018/06/27  05:03            30,189 LICENSE.txt

2018/06/27  05:03           608,911 NEWS.txt

2018/08/14  15:05            11,190 outfile.png

2018/06/27  05:01            99,992 python.exe

2018/06/27  05:00            59,032 python3.dll

2018/06/27  05:00         3,844,760 python37.dll

2018/06/27  05:01            98,456 pythonw.exe

2018/08/21  14:53    <DIR>          Scripts

2018/08/16  11:21    <DIR>          share

2018/07/26  11:10    <DIR>          tcl

2018/07/26  11:09    <DIR>          Tools

2018/08/21  14:49         3,051,365 Twisted-18.7.0-cp37-cp37m-win_amd64.whl

2018/06/27  04:02            89,752 vcruntime140.dll

               9 个文件      7,893,647 字节

              11 个目录 185,532,637,184 可用字节


>>> print(res.stderr.read().decode("gbk"))

控制台字体颜色设置

添加链接描述

迭代器

访问元素,可以记录元素的位置,但是只能前进,不能后退,两个基本方法
iter和next

>>> list = [1,2,3,4]
>>> it = iter(list)
>>> print(next(it))
1
>>> print(next(it))
2

用iter

>>> list = [1,3,5,7]
>>> it = iter(list)
>>> for x in it:
	print(x, end=" ")

	
1 3 5 7 

用Next

>>> import sys
>>> list = [1,2,3,4]
>>> it = iter(list)
>>> 
>>> while True:
	try:
		print(next(it))
	except StopIteration:
		sys.exit()

		
1
2
3
4
# eval:执行字符串类型的代码,并返回最终结果。
# eval('2 + 2')  # 4
#
# n = 81
# print(eval("n + 4"))  # 85
#
# eval('print(666)')  # 666
 exec:执行字符串类型的代码。
s = '''
for i in [1,2,3]:
    print(i)
'''
exec(s)
compile:将字符串类型的代码编译。代码对象能够通过exec语句来执行或者eval()进行求值。
'''
参数说明:   

1. 参数source:字符串或者AST(Abstract Syntax Trees)对象。即需要动态执行的代码段。  

2. 参数 filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。当传入了source参数时,filename参数传入空字符即可。  

3. 参数model:指定编译代码的种类,可以指定为 ‘exec’,’eval’,’single’。当source中包含流程语句时,model应指定为‘exec’;当source中只包含一个简单的求值表达式,model应指定为‘eval’;当source中包含了交互式命令语句,model应指定为'single'。
'''
>>> #流程语句使用exec
>>> code1 = 'for i in range(0,10): print (i)'
>>> compile1 = compile(code1,'','exec')
>>> exec (compile1)


>>> #简单求值表达式用eval
>>> code2 = '1 + 2 + 3 + 4'
>>> compile2 = compile(code2,'','eval')
>>> eval(compile2)


>>> #交互语句用single
>>> code3 = 'name = input("please input your name:")'
>>> compile3 = compile(code3,'','single')
>>> name #执行前name变量不存在
Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    name
NameError: name 'name' is not defined
>>> exec(compile3) #执行时显示交互命令,提示输入
please input your name:'pythoner'
>>> name #执行后name变量有值
"'pythoner'"
Python进阶之路》是一本非常值得推荐的Python进阶书籍。这本书由一位经验丰富的Python大牛所著,作者拥有超过20年的Python开发经验。这本书涵盖了许多Python进阶知识点,如元编程、动态属性、属性描述符、异步处理等。书中详细列举了这些高级特性的使用方法,并讲解得非常透彻。如果你想从入门迈向进阶,这本书是必备的参考资料。 另外,《Python Cookbook》也是一本非常受欢迎的Python进阶书籍。这本书总结了大量精妙的编程技巧和实用的技术,无论你是Python新手还是老手,都会从中收获很多。豆瓣评分高达9.2分,可见其受到广大读者的认可。 除了以上两本书,《Python进阶技巧》也是一本非常值得一读的进阶书籍。这本书的作者将许多代码简化成了一行,展现了Python的高级技巧。虽然有些地方可能看起来有些夸张,但它确实帮助你了解Python的特性和一些不错的功能。而且,在关键时刻,这种技巧还可以让你轻松搞定其他人需要十几行代码才能完成的任务。对于想要进阶的同学来说,这本书的阅读是非常适合的。 总而言之,《Python进阶之路》、《Python Cookbook》和《Python进阶技巧》都是非常优秀的Python进阶书籍,适合想要深入学习Python的读者。 : 引用自《Python进阶之路》 : 引用自《Python Cookbook》 : 引用自《Python进阶技巧》
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值