天天看点

从Python新手到高手的68行代码

文章目录

      • 基础入门
      • 菜鸟提升
      • 基础晋级
      • 高手之路
      • 内置包库
      • 奇技淫巧

基础入门

1

python

即在命令行输入

python

,进入

Python

的开发环境。

2

x = 1+2*3-4/5+6**2

加减乘除四则混合运算,可以当作计算器用了,其中

**

表示乘方。

3

print(x)

即输出

x

的值,如果感觉麻烦,可以直接输入

x

,然后回车,也能看到x的值。

4

if x>5 : print(x)

简单的判断,如果

x>5

,则打印

x

5

for i in range(10): print(i)

简单的循环,其中

range(10)

表示创建一个可迭代的自然序列,

range(10)

表示

0,1,2...10

6

'hello '+"world"

python中可以用单引号或双引号表示字符串,

+

可以拼接两个字符串。

7

def addOne(x):return x+1

python中通过

def

来声明函数,函数名称和函数主体之间用

:

分隔,声明上式之后可以直接在命令行中调用。

>>> def addOne(x):return x+1
...
>>> addOne(1)
2
           

8

x = [1,2,'abc',3,2]

python中可通过

[]

来创建一个列表,列表中的成员可以为任意数据类型。

>>> x = [1,2,'abc',3,2]
>>> x
[1, 2, 'abc', 3, 2]
           

9

x[0]

python中通过方括号和冒号来进行索引,且索引从0开始。

>>> x[0]
1
           

10

y = set(x)

set

为集合,集合中不允许存在相同的元素,所以将一个列表转成集合之后,会删除列表中的重复元素。

>>> y = set(x)
>>> y
{1, 2, 3, 'abc'}
           

菜鸟提升

11

pip install numpy

在命令行中运行

pip

命令,进行python相关包的安装。安装之后,再运行

python

进入python环境。

12

import numpy as np

导入

numpy

包,并给与其

np

的标识,从而我们可以通过

np.

的形式来调用

numpy

中的函数。

13

x = np.arange(10)

生成一个自然序列,与

range

,但是

np.arange

得到的可进行运算的数组(array)。

>>> x = np.arange(10)
>>> x
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
           

14

x**2

没什么好说的,只是演示以下array可以使用运算符。

>>> x**2
array([ 0,  1,  4,  9, 16, 25, 36, 49, 64, 81], dtype=int32)
           

15

x.tolist()**2

这是一行错误的代码,其中

x.tolist()

是将x从

array

转成

list

。然后再算其平方,然而列表(list)这种数据格式在python中是不能直接进行计算的,所以报了错。

>>> x.tolist()
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x.tolist()**2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
           

16-18

>>> if len(x)==5:print(x)
... elif len(x)==10: print(x.tolist()+x)
... else: print(x[0])
...
[ 0  2  4  6  8 10 12 14 16 18]
           

len

表示获取

x

的长度,python中通过

==

来判断二者是否相等。上式表示,如果x的长度等于5,则打印x;或者x的长度为10,则打印

x.tolist()+x

;如果x的长度为其他值,则打印

x[0]

由于x的长度是10,所以执行了第2行代码。而且我们发现,python非常智能地按照

array

的规则计算了

x.tolist()+x

。这说明,当表达式中同时存在

array

list

的时候,python会自动将

list

转为

array

19-20

>>> d = {"a":1,"b":2,"c":3}
>>> d["a"]
1
           

d即为字典,可通过键值对的形式进行索引。案例中,

"a","b","c"

为键(

key

),

1,2,3

为值(

value

),通过

key

来索引

value

,非常便利。

基础晋级

21

a = 1,2,3

逗号分隔的变量会默认组成元组,元组会根据等号左边变量的个数来进行赋值。

>>> a = 1,2,3
>>> a
(1, 2, 3)
           

22

a,b = 1,2

元组可以通过元素对应的位置来进行一一赋值,由此而带来的便利就是可以更快速地交换两个变量的值。

>>> a,b = 1,2
>>> a
1
>>> b
2
>>> b,a = a,b
>>> b
1
>>> a
2
           

23

print(f"a={a}")

在python中,字符串前面可有四种前缀,其中

f

代表字符串格式化,即format,在f字符串中,大括号内部会自动转换为变量。

>>> print(f"a={a}")
a=2
           

24

a = False if a==2 else True

在Python中,

False

True

为bool型的两个值。

在python中,可通过

if...else

构成三元表达式,上式可等价为响应的C语言

a = a==2 ? 0 : 1

>>> a = False if a==2 else True
>>> a
False
           

25

x = [i for i in range(10)]

在python中,可通过

for

循环来创建元组、列表以及字典。

>>> x = [i for i in range(10)]
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
           

26-30

def fac(n):
    if n == 0:
        return 1
    else:
        return n*fac(n-1) 
           

这是一个阶乘算法。在pyhton中,代码块以空格的形式存在。

高手之路

31

fac = lambda n : 1 if n==0 else n*fac(n-1)

这同样是一个阶乘算法,与26-30表示的是同一个函数。此即

lambda

表达式,可以更加方便地创建函数。

32

op = {"add":lambda a,b:a+b, "minus":lambda a,b:a-b}

Python中没有

switch..case

表达式,而字典+lambda表达式可以弥补这一点。上式中,

op["add"]

表示调用函数

lambda a,b:a+b

,即加法;

op["minus"]

表示调用函数

lambda a,b:a-b

,即减法。

正因

lambda

表达式并不需要命名,所以也称匿名函数。

>>> op = {"add":lambda a,b:a+b, "minus":lambda a,b:a-b}
>>> op["add"](3,4)
7
>>> op["minus"](3,4)
-1
           

33-34

while a<5:a+=1
else: print(f"a={a}")
           

while循环大家都十分了解,即当

a<5

时执行

a+=1

的程序。

else

表示当

a<5

不满足时执行的代码。

>>> while a<5:a+=1
... else: print(f"a={a}")
...
a=5
           

35-37

xs = []
for x in range(10): xs.append(x)
else : print(xs)
           

while..else

相似,

for

也有和

else

的组合,其语义也很雷同,表示当执行完

for

循环之后执行

else

的语句。

>>> xs = []
>>> for x in range(10): xs.append(x)
... else : print(xs)
...
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
           

38-40

from matplotlib import pyplot as plt
plt.plot(np.random.rand(10))
plt.show()
           

from...import

表示从

matplotlib

中导入

pyplot

matplotlib

是python中最常用的画图包,功能非常强大。

plt.plot

是最常用的绘图函数。

python

在执行绘图函数之后,会将图片放入内存,当使用

plt.show()

之后,才会将其显示到屏幕上。

>>> from matplotlib import pyplot as plt
>>> plt.plot(np.random.rand(10))
[<matplotlib.lines.Line2D object at 0x00000232FA511B10>]
>>> plt.show()
           
从Python新手到高手的68行代码

41-48

class person:
    def __init__(self,name): 
        self.name = name
    def selfIntro(self): 
        print(f"my Name is {self.name}")
    @staticmethod
    def say(string): 
        print(string)
           

尽管python主打函数式,但在python中,一切皆对象。而

class

则可以声明一个类。

在类中,通过

self

来声明类成员,类似有些语言中的

this.

__init__

为python内置的初始化函数,在类实例化之后,会首先运行这个函数。

@staticmethod

为静态类标识,静态类可以不经实例而使用。

>>> class person:
...     def __init__(self,name):
...         self.name = name
...     def selfIntro(self):
...         print(f"my Name is {self.name}")
...     @staticmethod
...     def say(string):
...         print(string)
...
>>> person.say("hello")
hello
>>> person.selfIntro()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: person.selfIntro() missing 1 required positional argument: 'self'
>>> Li = person("Li")
>>> Li.selfIntro()
my Name is Li
>>>
           

49

xs=[i for i in range(10) if i%2==0]

通过推导式来快速通过筛选来创建列表。

>>> xs=[i for i in range(10) if i%2==0]
>>> xs
[0, 2, 4, 6, 8]
           

50

d = dict([[1,2],[4,5],[6,7]])

通过

dict

可将列表转为字典,前提是列表中的元素必须为二元组。

>>> d = dict([[1,2],[4,5],[6,7]])
>>> d
{1: 2, 4: 5, 6: 7}
           

内置包库

51

time.time()

当然前提是要导入

import time

,这其实是个很常用的函数,以时间戳的形式返回当前的时间。

详情可查看python内置时间模块.

>>> import time
>>> time.time()
1634558595.5172253
           

52

calendar.prmonth(2021,10)

可打印日历。。。详情可参见python打印一整年的日历

>>> import calendar
>>> calendar.prmonth(2021,10)
    October 2021
Mo Tu We Th Fr Sa Su
             1  2  3
 4  5  6  7  8  9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
>>>
           

53

os.listdir(r"c:\Windows")

可返回文件夹内部的文件和子文件夹。其中

r

标识字符串中的

\

不用于转义。

>>> import os
>>> os.listdir(r"c:\Windows")
['addins', 'appcompat', 'apppatch', 'AppReadiness', 'assembly', 'bcastdvr', 'bfsvc.exe', ...
           

54

glob.glob(r"c:\Windows\*.ini")

可通过通配符返回文件夹内部的文件。

>>> import glob
>>> glob.glob(r"c:\Windows\*.exe")
['c:\\Windows\\bfsvc.exe', 'c:\\Windows\\explorer.exe', 'c:\\Windows\\HelpPane.exe', 'c:\\Windows\\hh.exe', 'c:\\Windows\\notepad.exe', 'c:\\Windows\\py.exe', 'c:\\Windows\\pyw.exe', 'c:\\Windows\\regedit.exe', 'c:\\Windows\\splwow64.exe', 'c:\\Windows\\Wiainst64.exe', 'c:\\Windows\\winhlp32.exe', 'c:\\Windows\\write.exe']
>>>
           

55-56

urllib

response = urllib.request.urlopen('https://blog.csdn.net/')
html = response.read()
           

urllib

是python内置的http解析请求库,是大多数爬虫学习者接触的第一个工具。

其中,

read()

用于读取网页数据,当然,得到的网页数据是未解码数据。

import urllib.request
response = urllib.request.urlopen('https://blog.csdn.net/')
html = response.read()
           

57-58 正则表达式re

content = html.decode('utf-8')
cn = re.findall(r"[\u4e00-\u9fa5]+", content)
           

此为正则表达式的简单应用,

re.findall

表示从字符串

content

中筛选出符合

r"[\u4e00-\u9fa5]+"

要求的值。所以第一步,是通过

utf-8

对content进行解码。

而在

utf-8

中,汉字的序号为

\u4e00-\u9fa5

;在正则表达式中,

[]

表示符合条件的集合,

+

表示出现任意多个符合条件的字符。

>>> import re
>>> content = html.decode('utf-8')
>>> cn = re.findall(r"[\u4e00-\u9fa5]+", content)
>>> cn[:20]
['博客', '专业', '技术发表平台', '博客为中国软件开发者', '从业人员', '初学者打造交流的专业', '技术发表平台', '全心致力于帮助开发者通过互联网分享知识', '让更多开发者从中受益', '一同和', '开发者用代码改变未来', '头部', '广告', '频道首页右侧', '打底', '头部', '广告', '题目征集', '你出我答', '做']
>>>
           

59-60 创建窗口程序

tkinter

frame = tkinter.Tk()
frame.mainloop()
           

其中

frame

即为tkinter创建的窗口,而

mainloop

表示进入窗口的消息循环。

从Python新手到高手的68行代码
>>> import tkinter
>>> frame = tkinter.Tk()
>>> frame.mainloop()
           

奇技淫巧

61

judge = lambda a,b,f1,f2 : (f1 if a>b else f2)(a,b)

表示,如果

a>b

则执行

f1(a,b)

,否则执行

f2(a,b)

62

eval('[a,b,c]')

eval

函数会把字符串转为可执行的表达式。

63

list(zip(*lst))

zip

可以像拉链一样将数组中对应的值缝合起来,以元组的形式重新存储。根据这个特性,可完成列表的"转置"。

>>> lst = [[1,2], [3,4], [5,6]]
>>> list(zip(*lst))
[(1, 3, 5), (2, 4, 6)]
           

64

max(set(lst),key=lst.count)

其中

lst

为列表,

count(i)

是列表的内置函数,表示统计

i

出现的个数。

set

表示将

lst

转为集合,从而剩排除重复值。

max(set(lst),key=lst.count)

表示通过

lst.count

这个指标来得到

set(lst)

中出现次数最多的那个值——即求众数。

65

dict(zip(myDict.values(),myDict.keys()))

通过

zip

实现字典的字符串互换操作。

66

[*a,*b]

*可以取出列表中的元素,所以

[*a,*b]

可以起到合并列表的作用。

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> [*a,*b]
[1, 2, 3, 4, 5, 6]
           

但星号索引的用途不止于此,在函数传参时也有意想不到的后果

>>> addd = lambda a,b,c : a+b+c
>>> addd(*a)
6
           

67

{**a,**b}

双星号可以取出字典中的元素,实现字典合并的功能。

>>> a = {"b":1,"c":2}
>>> b = {"d":3,"e":4}
>>> {**a,**b}
{'b': 1, 'c': 2, 'd': 3, 'e': 4}
           

同样,双星号索引的用途也不止于此

>>> addd(3,**a)
6
           

68

s == s[::-1]

在python中,对列表或者字符串采用

:

进行索引,例如

a:b

指的是从a到b的数据;当采用双引号

::

时,引号间的值的意义就发生了变化,例如

a:b:c

表示从a到b,间隔为c的数据。

据此,可以得到

::-1

表示将字符串颠倒过来,据此可以判断一个字符串是否为回文结构。

尽管这些代码还没涉及到多线程等功能(主要是行数比较多),也没涉及到和类相关的一些功能(也是因为行数多),但如果您全都一目了然或者曾经用过,那么我愿称君为高手!