Skip to content

Python 基础

Python 简介

Python 的创始人为荷兰人吉多·范罗苏姆(Guido van Rossum)。

初见Python

安装好 Python 之后,在命令行下输入:python 进入解释器,接下来就可以input 任意代码

shell
print "hello world!"

拓展知识 凯撒密码

input

python
import this

output

The Zen of Python, by Tim Peters

Beautiful is better than ugly.

Explicit is better than implicit.

Simple is better than complex.

Complex is better than complicated.

Flat is better than nested.

Sparse is better than dense.

Readability counts.

Special cases aren't special enough to break the rules.

Although practicality beats purity.

Errors should never pass silently.

Unless explicitly silenced.

In the face of ambiguity, refuse the temptation to guess.

There should be one-- and preferably only one --obvious way to do it.

Although that way may not be obvious at first unless you're Dutch.

Now is better than never.

Although never is often better than right now.

If the implementation is hard to explain, it's a bad idea.

If the implementation is easy to explain, it may be a good idea.

Namespaces are one honking great idea -- let's do more of those!

源代码解析

python
s = """Gur Mra bs Clguba, ol Gvz Crgref

Ornhgvshy vf orggre guna htyl.
Rkcyvpvg vf orggre guna vzcyvpvg.
Fvzcyr vf orggre guna pbzcyrk.
Pbzcyrk vf orggre guna pbzcyvpngrq.
Syng vf orggre guna arfgrq.
Fcnefr vf orggre guna qrafr.
Ernqnovyvgl pbhagf.
Fcrpvny pnfrf nera'g fcrpvny rabhtu gb oernx gur ehyrf.
Nygubhtu cenpgvpnyvgl orngf chevgl.
Reebef fubhyq arire cnff fvyragyl.
Hayrff rkcyvpvgyl fvyraprq.
Va gur snpr bs nzovthvgl, ershfr gur grzcgngvba gb thrff.
Gurer fubhyq or bar-- naq cersrenoyl bayl bar --boivbhf jnl gb qb vg.
Nygubhtu gung jnl znl abg or boivbhf ng svefg hayrff lbh'er Qhgpu.
Abj vf orggre guna arire.
Nygubhtu arire vf bsgra orggre guna *evtug* abj.
Vs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn.
Vs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn.
Anzrfcnprf ner bar ubaxvat terng vqrn -- yrg'f qb zber bs gubfr!"""

d = {}  #初始化一个空字典 d
for c in (65, 97):         # 外层循环遍历两个字符 c,分别是大写字母 'A'(ASCII码为65)和小写字母 'a'(ASCII码为97)
    for i in range(26):     # 内层循环遍历26个字母,代表英文字母表中的所有字母。
        d[chr(i+c)] = chr((i+13) % 26 + c)  # 最后,将加密的字符作为键,解密后的字符作为值,存储在字典 d 中。

print "".join([d.get(c, c) for c in s])

最后一行是是对加密文本 s 进行解密的操作。它使用列表推导式遍历字符串 s 中的每个字符 c。对于每个字符,d.get(c, c) 会尝试从字典 d 中获取对应的解密字符。如果 c 是一个字母并且已经被加密,get 方法会返回解密后的字符;如果 c 不是一个字母或者没有被加密(例如空格、标点符号等),get 方法会返回 c 本身。然后,join 函数将这些字符连接成一个新的字符串,即解密后的文本。

:::

基本语法

?

? 查看帮助

?? 查看帮助和函数源代码

_ 可以作为上一个cell 的输出结果

! 可以执行系统命令

python
!ping baidu.com

解释器

通常我们并不使用Python自带的解释器python,而是使用另一个比较方便的解释器——ipython解释器,

ipython解释器提供了很多以百分号%开头的magic命令

python
# 查看所有的 magic 命令
%lsmagic

line magic 以一个百分号开头,作用与一行;

cell magic 以两个百分号开头,作用于整个cell。

最后一行Automagic is ON, % prefix IS NOT needed for line magics.说明在此时即使不加上%也可以使用这些命令。

命令描述备注
%whos查看当前变量空间
%reset -f重置当前变量空间
%pwd查看当前工作的文件夹
%mkdir新建文件夹
%cd改变工作文件夹:
%%writefile将cell中的内容写入文件:
%ls列出文件
%run运行代码
%rmdir删除文件夹
%hist查看历史命令

运行notebook

python
ipython notebook

会打开一个notebook本地服务器,一般地址是:http://localhost:8888

Anaconda

简介

Anaconda是一个很好用的Python IDE, 它集成了很多科学计算需要使用的python第三方工具包。开发者主要用该软件进行python虚拟环境的构建

下载和更新

官网:https://www.anaconda.com/ 官方文档:http://conda.pydata.org/docs/

第一次安装好 Anaconda 以后,可以在命令行输入以下命令使 Anaconda 保持最新:

shell
conda update conda
conda update numpy=1.8.1     # 可以指定版本号
conda update anaconda

基本命令

查看conda 信息

shell
!conda info

安装,更新,卸载第三方的 python 工具包

shell

conda install <some package>
conda update <some package>
conda remove <some package> numpy=1.8.1

创建一个新环境

shell
conda create -n <环境名> python=3.3

进入某个环境

shell
activate <环境名>

调用spyder 编辑器

Anaconda 默认使用的编辑器是 spyder,可以在命令行下输入:

shell
spyder

Python 数据基础

Python 数据类型

常用数据类型 Common Data Types

类型例子
整数-100
浮点数3.1416
字符串'hello'
列表[1, 1.2, 'hello']
字典{'dogs': 5, 'pigs': 3}
Numpy数组array([1, 2, 3])

其他类型 Others

类型例子
长整型1000000000000L
布尔型True, False
元组('ring', 1000)
集合{1, 2, 3}
Pandas类型DataFrame, Series
自定义Object Oriented Classes

字符串 String

  • 字符串的生成,单引号与双引号是等价的:
  • 三引号用来输入包含多行文字的字符串:
python
s = """hello
world"""

查看字符串长度

python
len(s)

字符串索引

在Python中,字符串是可以被索引的序列类型,其中每个字符都有一个对应的索引,从0开始计数。 下面的例子就是对变量S 的字符串进行索引

python
s[0] # h
s[-1] # d
s[0:4] # hello

字符串的分割:

python
s = "hello world"
s.split()

列表 List

Python用[]来生成列表

列表样式 [1, 2.0, 'hello', 6.0, 'world']

向列表中添加元素:

python
l.append("world") 
# l 是一个列表变量,

集合 Set

Python用{}来生成集合,集合中不含有相同元素。

向集合中添加元素:

python
s.add(1)

集合的交、并、差、对称差

python
a = {1, 2, 3, 4}
b = {2, 3, 4, 5}
a & b # 交  {2, 3, 4}
a | b # 并  {1, 2, 3, 4, 5}
a - b # 差  {1}
a ^ b # 对称差  指不同集合中 不重叠部分的并集
a ^ b= a - b | b - a

字典 Dictionary

Python用{key:value}来表示

查看字典某个key 对应的value

python
d["key"]  # 注意 是中括号,把key看成索引 就容易记

修改、插入键值

python
d["key"] =2  # 如果修改时 输入key为新键 时 自动插入

列出所有的key、所有的值、所有的键值对

python
d.keys()
d.values()
d.items()

# 注意结尾有个s

数组 Numpy Arrays

Numpy数组 可以进行很多列表不能进行的运算。

python
# 导入包
from numpy import array

画图 Polt

Python提供了一个很像MATLAB的绘图接口。

python
%matplotlib inline
from matplotlib.pyplot import plot
plot(a, a**2)

循环 Loop

python
line = '1 2 3 4 5'
fields = line.split()
fields

total = 0
for field in fields:
    total += int(field)
total

Python中有一种叫做列表推导式(List comprehension)的用法:

python
numbers = [int(field) for field in fields]
sum(numbers)

# 写在一行
sum([int(field) for field in line.split()])

文件操作 File IO

读写文件

python
# 读文件
f = open('data.txt')
data = []
for line in f:
    data.append([int(field) for field in line.split()])
f.close()
data

# 写文件
f = open('data.txt', 'w')
f.write('1 2 3 4\n')
f.write('2 3 4 5\n')
f.close()

# 删除文件
import os
os.remove('data.txt')

函数 Function

Python用关键词def来定义函数。

模块 Module

Python中使用import关键词来导入模块。

类 Class

class来定义一个类。 Person(object)表示继承自object类; __init__函数用来初始化对象; self表示对象自身, 类似于C Java里面this。

python
class Person(object):
    def __init__(self, first, last, age):
        self.first = first
        self.last = last
        self.age = age
    def full_name(self):
        return self.first + ' ' + self.last

构建新对象:

python
person = Person('Mertle', 'Sedgewick', 52)

调用对象的属性:

python
person.first
# 'Mertle'

调用对象的方法:

python
person.full_name()
# 'Mertle Sedgewick'

修改对象的属性:

python
person.last = 'Smith'

添加新属性,d是之前定义的字典:

python
person.critters = d
person.critters
{'cats': 4, 'dogs': 2, 'pigs': 7}

© 2023-2024 LiuJingcheng. 保留所有权利。