30分钟迅速上手python

我从两年前接触python,到现在python已经陪伴我渡过了我的大半个职业生涯,用过Django开发个人博客,用过pandas、numpy做过数据分析,还用过scikit-learn的数据挖掘算法,还使用过spider写爬虫,但是种种过往在脑中好似一场云烟,经历过却什么都没留下,所以从头开始梳理,将Python的相关知识点一一记录下来。
我一直使用的是经典2.7,官方称2020后将停止对2.x的维护,但是我还是习惯使用2.7版本。另外可以使用from __future__ import module 这种形式在2.x中使用3.x的方法。

# 使用数字符号可以注释单行.

""" 强调内容
多行注释可以使用三个 "
"""

1. 原始数据类型和操作符


# 你的数字
3  # => 3

# 简单的数学计算
1 + 1  # => 2
8 - 1  # => 7
10 * 2  # => 20
35 / 5  # => 7

# 除法相对来说有点麻烦,因为除法的结果是整数还是浮点数是自动的。
5 / 2  # => 2

# 为了解决除法,我们需要了解浮点数.
2.0  # 这就是一个浮点数
11.0 / 4.0  # => 2.75 啊哈哈...是不是好多了

# 整除的结果无论是正数还是负数都会截断.
5 // 3  # => 1
5.0 // 3.0  # => 1.0 # works on floats too
-5 // 3  # => -2
-5.0 // 3.0  # => -2.0

# 注意我们可以通过导入模块的方式使用一个/就进行正常的除法.
from __future__ import division

11 / 4  # => 2.75  ...normal division
11 // 4  # => 2 ...floored division

# 模的操作
7 % 3  # => 1

# 求幂
2 ** 4  # => 16

# 使用括号强制定义优先级
(1 + 3) * 2  # => 8

# 布尔操作
# 注意 "and" 和"or" 是要区分大小写的
True and False  # => False
False or True  # => True

# 注意用整数进行布尔操作
0 and 2  # => 0
-5 or 0  # => -5
0 == False  # => True
2 == True  # => False
1 == True  # => True

# 用not来否定
not True  # => False
not False  # => True

# 等于是 ==
1 == 1  # => True
2 == 1  # => False

# 不相等是 !=
1 != 1  # => False
2 != 1  # => True

# 更多的比较
1 < 10  # => True
1 > 10  # => False
2 <= 2  # => True
2 >= 2  # => True

# 可以进行一串比较!
1 < 2 < 3  # => True
2 < 3 < 2  # => False

# 可以使用 " 或 '来创造字符串
"This is a string."
'This is also a string.'

# 字符串还可以进行相加,代表拼接!
"Hello " + "world!"  # => "Hello world!"
# 没有 '+' 也可以进行拼接
"Hello " "world!"  # => "Hello world!"

# 增加更多
"Hello" * 3  # => "HelloHelloHello"

# 一个字符串可以被看做字符串列表
"This is a string"[0]  # => 'T'

# 可以获取字符串的长度
len("This is a string")  # => 16

# 使用 % 来对字符串进行格式化,但是在3.1后面的版本将会被弃用.
x = 'apple'
y = 'lemon'
z = "The items in the basket are %s and %s" % (x, y)

# 还有一种新的方法是使用format方法对字符串进行格式化,而且这也是首选的方法
"{} is a {}".format("This", "placeholder")
"{0} can be {1}".format("strings", "formatted")
# You can use keywords if you don't want to count.
"{name} wants to eat {food}".format(name="Bob", food="lasagna")

# None 是一个对象
None  # => None

# 我们要使用"is"来比较一个对象是否为None,而不是"==" 
"etc" is None  # => False
None is None  # => True

# 'is'可以测试对象的身份,但这个是对于对象来说有用,对于原始的值来说只能是然并卵

# 任何一个对象都可以被用在一个布尔环境里面.
# 下面这些值被认为是错误的:
#    - None
#    - zero of any numeric type (e.g., 0, 0L, 0.0, 0j)
#    - empty sequences (e.g., '', (), [])
#    - empty containers (e.g., {}, set())
#    - instances of user-defined classes meeting certain conditions
#      see: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__
#
# 其它的值被认为是正确的 (使用 bool() 函数返回的将是 True).
bool(0)  # => False
bool("")  # => False

2. 变量和集合


# Python 又一个打印语句
print "I'm Python. Nice to meet you!"  # => I'm Python. Nice to meet you!

# 从控制台上获得输入数据的简单方法
input_string_var = raw_input("Enter some data: ")  # 得到的是一个字符串
input_var = input("Enter some data: ")  # 将这个数据的值作为python代码
# 警告: 建议谨慎使用 input() 方法
# 注意: 在 python 3, input() 被弃用,并且raw_input() 重命名为 input()

# 在赋值变量前不需要声明,这个不像C++那样繁琐.
some_var = 5  # 惯例是使用小写和下划线
some_var  # => 5

# 使用一个之前没有赋值的变量是一种异常.
# 看报错内容可以了解更多的异常信息.
some_other_var  # 报 name error

# 使用一个表达式
"yahoo!" if 3 > 2 else 2  # => "yahoo!"

# 空列表
li = []
# 直接赋值列表
other_li = [4, 5, 6]

# 使用 append 方法为列表的末尾添加成员
li.append(1)  # li 现在是 [1]
li.append(2)  # li 现在是 [1, 2]
li.append(4)  # li 现在是 [1, 2, 4]
li.append(3)  # li 现在是 [1, 2, 4, 3]
# 使用 pop 方法可以从列表的末尾删除一个成员
li.pop()  # => 3 and li 现在是 [1, 2, 4]
# Let's put it back
li.append(3)  # li 现在又是 [1, 2, 4, 3] .

# 访问列表就跟访问数组一样
li[0]  # => 1
# 分配新值给索引指向的值
li[0] = 42
li[0]  # => 42
li[0] = 1  # 注意:把它设置成原来的值
# 查看最后一个元素
li[-1]  # => 3

# 如果查询的是一个超出索引的值就会报错
li[4]  # Raises an IndexError

# 你可以使用切片语法获取一个范围内的值.
# (开始和结束取决于你的数字位置.)
li[1:3]  # => [2, 4]
# 省略开始
li[2:]  # => [4, 3]
# 省略结束
li[:3]  # => [1, 2, 4]
# 每两条选择一个
li[::2]  # =>[1, 4]
# 反转整个列表
li[::-1]  # => [3, 4, 2, 1]
# 把他们结合起来做一个更先进的切片
# li[start:end:step]

# 使用"del"删除列表中的任意元素
del li[2]  # li is now [1, 2, 3]

# 通过列表相加的方式得到一个新列表
li + other_li  # => [1, 2, 3, 4, 5, 6]
# 注意: 原来的列表的值是没有改变的.

# 使用"extend()"方法对一个列表添加另一个列表
li.extend(other_li)  # 现在li变成了 [1, 2, 3, 4, 5, 6]

# 删除第一个出现的值
li.remove(2)  # li is now [1, 3, 4, 5, 6]
li.remove(2)  # Raises a ValueError as 2 is not in the list

# 在指定的索引出插入一个值
li.insert(1, 2)  # li is now [1, 2, 3, 4, 5, 6] again

# 找到这个值对应的索引
li.index(2)  # => 1
li.index(7)  # Raises a ValueError as 7 is not in the list

# 使用 "in" 检查元素是否在列表中
1 in li  # => True

# 使用 "len()" 查看列表的长度
len(li)  # => 6

# 元组跟列表很像,但是不能改变.
tup = (1, 2, 3)
tup[0]  # => 1
tup[0] = 3  # Raises a TypeError

# 对于列表的很多操作,在元组中同样也可以
len(tup)  # => 3
tup + (4, 5, 6)  # => (1, 2, 3, 4, 5, 6)
tup[:2]  # => (1, 2)
2 in tup  # => True

# 你可以直接将元组或者列表直接赋值给变量
a, b, c = (1, 2, 3)  # a is now 1, b is now 2 and c is now 3
d, e, f = 4, 5, 6  # you can leave out the parentheses
# 如果没有括号,将会默认创建一个元组
g = 4, 5, 6  # => (4, 5, 6)
# 现在如果要交换两个值将会变得非常简单
e, d = d, e  # d is now 5 and e is now 4

# 字典主要存储映射
empty_dict = {}
# 直接赋值字典
filled_dict = {"one": 1, "two": 2, "three": 3}

# 使用 [] 查找字典里的值
filled_dict["one"]  # => 1

# 使用 "keys()" 可以得到所有的键值
filled_dict.keys()  # => ["three", "two", "one"]
# 注意- 字典的键是无须的,所以得到的值可能跟你一开始定义的不一样

# 使用 "values()" 可以得到所有的值
filled_dict.values()  # => [3, 2, 1]
# 注意- 同样的值是无须的.

# 使用"items()"可以得到一个以列表中的元组形式的“键值-值”对
filled_dict.items()  # => [("one", 1), ("two", 2), ("three", 3)]

# 使用 "in" 检查元素键是否在字典中
"one" in filled_dict  # => True
1 in filled_dict  # => False

# 查询不存在的健是一个 KeyError
filled_dict["four"]  # KeyError

# 使用 "get()" 可以避免上面的错误,如果没有就会返回None
filled_dict.get("one")  # => 1
filled_dict.get("four")  # => None
# 通过设置默认值的方式,可以显示没有键情况下的值
filled_dict.get("one", 4)  # => 1
filled_dict.get("four", 4)  # => 4
# 注意这时候的 filled_dict.get("four") 还是 => None
# (get 方法并不能添加字典里面的值)

# 设置健值的方法跟列表的类似,直接赋值
filled_dict["four"] = 4  # now, filled_dict["four"] => 4

# 使用 "setdefault()" 方法,当键不存在的时候就设置这个键和值,但是如果存在就不进行改变
filled_dict.setdefault("five", 5)  # filled_dict["five"] is set to 5
filled_dict.setdefault("five", 6)  # filled_dict["five"] is still 5

# 集合跟列表也很类似,但是不能包含重复值
empty_set = set()
# 使用 "set()" 对一群治进行初始化
some_set = set([1, 2, 2, 3, 4])  # some_set is now set([1, 2, 3, 4])

# 虽然它看起来是经过排序的,但是实际上它是无序的
another_set = set([4, 3, 2, 2, 1])  # another_set is now set([1, 2, 3, 4])

# 从 2.7 开始, {} 可以用来声明一个集合
filled_set = {1, 2, 2, 3, 4}  # => {1, 2, 3, 4}

# 向集合中添加更多的成员
filled_set.add(5)  # filled_set is now {1, 2, 3, 4, 5}

# 使用 & 对集合进行交集操作
other_set = {3, 4, 5, 6}
filled_set & other_set  # => {3, 4, 5}

# 使用 | 对集合进行合集操作
filled_set | other_set  # => {1, 2, 3, 4, 5, 6}

# 使用 - 可以得到补集
{1, 2, 3, 4} - {2, 3, 5}  # => {1, 4}

# 使用 ^ 得到交集的补集
{1, 2, 3, 4} ^ {2, 3, 5}  # => {1, 4, 5}

# 检查左边是否是右边的超集
{1, 2} >= {1, 2, 3}  # => False

# 检查左边是否是右边的子集
{1, 2} <= {1, 2, 3}  # => True

# 使用 in 检查是否在集合中
2 in filled_set  # => True
10 in filled_set  # => False
10 not in filled_set # => True

# 查看变量的数据类型
type(li)   # => list
type(filled_dict)   # => dict
type(5)   # => int

3. 控制流


# 先来一个变量
some_var = 5

# 这里又一个声明,缩进在python里非常重要!
# 打印"some_var is smaller than 10"
if some_var > 10:
    print "some_var is totally bigger than 10."
elif some_var < 10:  # 这个 else 字句是可有可无的,根据需要.
    print "some_var is smaller than 10."
else:  # 这个也是.
    print "some_var is indeed 10."

"""
For 循环在列表中遍历
prints:
    dog is a mammal
    cat is a mammal
    mouse is a mammal
"""
for animal in ["dog", "cat", "mouse"]:
    # 你可以使用 {0} 得到format里面的字符串. (See above.)
    print "{0} is a mammal".format(animal)

"""
"range(number)" 返回一个数字列表
from 0 to 给出去的数字
prints:
    0
    1
    2
    3
"""
for i in range(4):
    print i

"""
"range(lower, upper)" 返回一个数字列表
from 小的数字 to 大的数字
prints:
    4
    5
    6
    7
"""
for i in range(4, 8):
    print i

"""
While 循环遇到条件就不在运行.
prints:
    0
    1
    2
    3
"""
x = 0
while x < 4:
    print x
    x += 1  # 缩写 x = x + 1

# 处理异常使用 try/except 模块
try:
    # 使用 "raise" 来提示错误内容
    raise IndexError("This is an index error")
except IndexError as e:
    pass  # Pass 就是一个空操作,但是你要写在这里.
except (TypeError, NameError):
    pass  # 如果需要,可以将多个异常处理掉.
else:  # 可用可不用,根据需求,但是要在所有的except后面而且要符合逻辑
    print "All good!"  # 只会在没有报错的时候运行
finally:  # 在所有情况下都会执行
    print "We can clean up resources here"

# 你可以使用下面这个字句代替 try/finally 
with open("myfile.txt") as f:
    for line in f:
        print line

4. 函数


# 使用 "def" 来创建一个函数
def add(x, y):
    print "x is {0} and y is {1}".format(x, y)
    return x + y  # 使用 return 字句返回值


# 使员工参数调用函数
add(5, 6)  # => 打印 "x is 5 and y is 6" 并且返回值 11

# 还可以使用关键字参数调用函数
add(y=6, x=5)  # 关键字参数不需要在意排序.


# 你可以使用 * 定义函数的位置变量参数,使用的时候会被当做一个元组
def varargs(*args):
    return args


varargs(1, 2, 3)  # => (1, 2, 3)


# 你还可以使用 ** 定义函数的关键字变量参数,使用的时候会被当做一个字典
def keyword_args(**kwargs):
    return kwargs


# 调用之后看看会发生什么
keyword_args(big="foot", loch="ness")  # => {"big": "foot", "loch": "ness"}


# 只要你想要,两个一起上也可以
def all_the_args(*args, **kwargs):
    print args
    print kwargs


"""
all_the_args(1, 2, a=3, b=4) prints:
    (1, 2)
    {"a": 3, "b": 4}
"""

# 调用函数的时候,你也可以对 args/kwargs 做相反的操作!
# 先定义相关的args/kwargs,然后使用 * 传递位置参数、使员工 **传递关键字参数.
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
all_the_args(*args)  # 相当于 all_the_args(1, 2, 3, 4)
all_the_args(**kwargs)  # 相当于 all_the_args(a=3, b=4)
all_the_args(*args, **kwargs)  # 相当于 all_the_args(1, 2, 3, 4, a=3, b=4)


# 还可以分别使用 * and ** 来接受并传递其他函数的参数
def pass_all_the_args(*args, **kwargs):
    all_the_args(*args, **kwargs)
    print varargs(*args)
    print keyword_args(**kwargs)


# 函数范围
x = 5


def set_x(num):
    # 局部变量 x 跟全局变量 x 不一样
    x = num  # => 43
    print x  # => 43

def set_global_x(num):
    global x
    print x  # => 5
    x = num  # 全局变量 x 现在变成了 6
    print x  # => 6

set_x(43)
set_global_x(6)


# Python 有第一类型
"""
备注:根据变量的取值范围、可操作性、可赋值性可以三种类型:
一级:可以作为参数传递也可以作为结果返回;
二级:可以作为参数传递,但是不能作为结果返回,也不能复制给变量;
三级:连作为参数传递也不行。
"""
def create_adder(x):
    def adder(y):
        return x + y

    return adder


add_10 = create_adder(10)
add_10(3)  # => 13

# 还有一些匿名函数
(lambda x: x > 2)(3)  # => True
(lambda x, y: x ** 2 + y ** 2)(2, 1)  # => 5

# 还有内置的一些高阶函数
map(add_10, [1, 2, 3])  # => [11, 12, 13],map根据给定的函数对指定序列做映射
map(max, [1, 2, 3], [4, 2, 1])  # => [4, 2, 3],提供两个列表,对相同的位置进行max

filter(lambda x: x > 5, [3, 4, 5, 6, 7])  # => [6, 7]

# 我们可以使用列表来更好的理解 maps 和 filters 函数
[add_10(i) for i in [1, 2, 3]]  # => [11, 12, 13]
[x for x in [3, 4, 5, 6, 7] if x > 5]  # => [6, 7]

# 你也可以构造字典或集合去理解.
{x for x in 'abcddeef' if x in 'abc'}  # => {'a', 'b', 'c'}
{x: x ** 2 for x in range(5)}  # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

5. 类


# 我们从对象的子类中得到一个类.
class Human(object):
    # 类的属性. 它会被这个类的所有实例共享
    species = "H. sapiens"

    # 当类被实例化时,称为基本的初始化.
    # 注意双前下划线和双后下划线表示python所使用的对象和或属性,它们存在于用户空盒子的名称空间中,这些名字你最好别自己命名
    def __init__(self, name):
        # 分配参数给这个实例的 name 属性
        self.name = name

        # 初始化属性
        self.age = 0

    # 一个实例的方法. 所有的方法使用 "self" 作为第一个参数
    def say(self, msg):
        return "{0}: {1}".format(self.name, msg)

    # 一个类方法是所有实例之间共享的
    # 它们作为第一参数,称为调用类
    @classmethod
    def get_species(cls):
        return cls.species

    # 在没有类和实例的情况下调用静态方法
    @staticmethod
    def grunt():
        return "*grunt*"

    """
    丝毫没有get到最后这三种方法的用处
    """
    # property 方法就像 getter 方法.
    # 它将类方法转化为一个相同名称的只读属性.
    @property
    def age(self):
        return self._age

    # 允许去设置属性
    @age.setter
    def age(self, age):
        self._age = age

    # 允许删除属性
    @age.deleter
    def age(self):
        del self._age


# 初始化类
i = Human(name="Ian")
print i.say("hi")  # prints out "Ian: hi"

j = Human("Joel")
print j.say("hello")  # prints out "Joel: hello"

# 调用类方法
i.get_species()  # => "H. sapiens"

# 改变共有属性
Human.species = "H. neanderthalensis"
i.get_species()  # => "H. neanderthalensis"
j.get_species()  # => "H. neanderthalensis"

# 调用静态方法
Human.grunt()  # => "*grunt*"

# 更新属性
i.age = 42

# 得到属性
i.age  # => 42

# 删除属性
del i.age
i.age  # => raises an AttributeError

####################################################
# 6. 模块
####################################################

# 引入模块
import math

print math.sqrt(16)  # => 4

# 从模块中引入指定函数
from math import ceil, floor

print ceil(3.7)  # => 4.0
print floor(3.7)  # => 3.0

# 从模块中引入所有的函数.
# Warning: 不推荐这么做
from math import *

# 还可以对模块重命名
import math as m

math.sqrt(16) == m.sqrt(16)  # => True
# y你可以测试下这些其实等价的
from math import sqrt

math.sqrt == m.sqrt == sqrt  # => True

# Python的模块值是普通的文件.你可以自己写个,然后引入. 模块的名称就是文件的名称.

# 你可以找出是哪些函数和属性定义了一个模块
import math

dir(math)


# 如果在现有模块的文件夹中有一个脚本名称为 math.py ,这个脚本将会代替Python的自建模块,这是因为本地的文件优先级高于自建的库

7. 高级(暂未涉及)


# 生成器
# A generator "generates" values as they are requested instead of storing everything up front

# The following method (*NOT* a generator) will double all values and store it in `double_arr`. For large size of iterables, that might get huge!
def double_numbers(iterable):
    double_arr = []
    for i in iterable:
        double_arr.append(i + i)
    return double_arr


# Running the following would mean we'll double all values first and return all of them back to be checked by our condition
for value in double_numbers(range(1000000)):  # `test_non_generator`
    print value
    if value > 5:
        break


# We could instead use a generator to "generate" the doubled value as the item is being requested
def double_numbers_generator(iterable):
    for i in iterable:
        yield i + i


# Running the same code as before, but with a generator, now allows us to iterate over the values and doubling them one by one as they are being consumed by our logic. Hence as soon as we see a value > 5, we break out of the loop and don't need to double most of the values sent in (MUCH FASTER!)
for value in double_numbers_generator(xrange(1000000)):  # `test_generator`
    print value
    if value > 5:
        break

# BTW: did you notice the use of `range` in `test_non_generator` and `xrange` in `test_generator`?
# Just as `double_numbers_generator` is the generator version of `double_numbers`
# We have `xrange` as the generator version of `range`
# `range` would return back and array with 1000000 values for us to use
# `xrange` would generate 1000000 values for us as we request / iterate over those items

# Just as you can create a list comprehension, you can create generator comprehensions as well.
values = (-x for x in [1, 2, 3, 4, 5])
for x in values:
    print(x)  # prints -1 -2 -3 -4 -5 to console/terminal

# You can also cast a generator comprehension directly to a list.
values = (-x for x in [1, 2, 3, 4, 5])
gen_to_list = list(values)
print(gen_to_list)  # => [-1, -2, -3, -4, -5]

# 装饰器
# A decorator is a higher order function, which accepts and returns a function.
# Simple usage example – add_apples decorator will add 'Apple' element into fruits list returned by get_fruits target function.
def add_apples(func):
    def get_fruits():
        fruits = func()
        fruits.append('Apple')
        return fruits
    return get_fruits

@add_apples
def get_fruits():
    return ['Banana', 'Mango', 'Orange']

# Prints out the list of fruits with 'Apple' element in it: Banana, Mango, Orange, Apple
print ', '.join(get_fruits())

# in this example beg wraps say
# Beg will call say. If say_please is True then it will change the returned message
from functools import wraps


def beg(target_function):
    @wraps(target_function)
    def wrapper(*args, **kwargs):
        msg, say_please = target_function(*args, **kwargs)
        if say_please:
            return "{} {}".format(msg, "Please! I am poor :(")
        return msg

    return wrapper


@beg
def say(say_please=False):
    msg = "Can you buy me a beer?"
    return msg, say_please


print say()  # Can you buy me a beer?
print say(say_please=True)  # Can you buy me a beer? Please! I am poor :(

猜你喜欢

转载自blog.csdn.net/qq_35318838/article/details/79758016