Python 基础知识汇总

前言

安装 ipython,方便命令行编辑:

pip install ipython==5.7.0

数据类型和操作

数据类型

  • 一切是皆对象
  • int, float, boolean
  • string, list, tuple
  • dict, set
  • file

逻辑判断符

  •   <-> or
  • && <-> and
  • ! <-> not

条件语句

if a > 0:
    print '+'
elif a < 0:
    print '-'
else:
    pass

三重表达式

'event' if a%2 == 0 else 'odd'
'odd' if a%2 else 'event'

字符串

s = 'ilovepython'

Python访问字符串的值:

  • 索引从左到右,默认0开始的,最大范围是字符串长度 -1
  • 索引从右到左,默认-1开始的,最大范围是字符串开头
s[0]    # i
s[1:5]  # love
s[-6:]  # python
s[::-1] # nohtypevoli
        # 等价于s[-1::-1]
        # step为负数,从左向右截取
s = 'ilovepython'
print s.startswitch('ilo')  # True
print s.endswitch('ilo')    # True
s.count('o')    # 2
s.find('o')     # 6
s.index('o')    # 6

区别:

In [1]: help("".index)
Help on built-in function index:

index(...)
    S.index(sub [,start [,end]]) -> int

    Like S.find() but raise ValueError when the substring is not found.


In [2]: help("".find)
Help on built-in function find:

find(...)
    S.find(sub [,start [,end]]) -> int

    Return the lowest index in S where substring sub is found,
    such that sub is contained within S[start:end].  Optional
    arguments start and end are interpreted as in slice notation.

    Return -1 on failure.

技巧汇总

在命令窗口执行:

help(<>)
dir(<>)

字符串

"this is a    new string".split()
# ['this', 'is', 'a', 'new', 'string']

' '.join(['this', 'is', 'a', 'new', 'string'])
'this is a new string'

'*'.join(['this', 'is', 'a', 'new', 'string'])
'this*is*a*new*string'

输出

"I'm from %s. %s is the capital of %s" % ("ZhengZhou", "ZhengZhou", "Henan")
# I'm from ZhengZhou. ZhengZhou is the capital of Henan

"I'm from {}. {} is the capital of {}".format("ZhengZhou", "ZhengZhou", "Henan")
# I'm from ZhengZhou. ZhengZhou is the capital of Henan

"I'm from {city}. {city} is the capital of {province}".format(city="ZhengZhou", province="Henan")
# I'm from ZhengZhou. ZhengZhou is the capital of Henan

编码

# -*- coding: UTF-8 -*- 或者 #coding=utf-8

list comprehension

fruits = ['apple', 'banana', 'orange']
big_fruits = [list(fruits) for i in range(3)]

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

tuple

(a, b)

sequence ( string list tuple )

str = "abcdef"
a_list = list(str)
a_list
# ['a', 'b', 'c', 'd', 'e', 'f']

a_tuple = tuple(a_list)
a_tuple
# ('a', 'b', 'c', 'd', 'e', 'f')

''.join(a_tuple)
'abcdef'
# -*- coding: utf-8 -*-


def t(arr):
    r = []
    for i, e in list(enumerate(arr)):
        if i%2:
            r.append((arr[i-1], e))
    if len(arr)%2:
        r.append((arr[-1], None))
    return r


def t2(arr):
    return [(arr[i], arr[i + 1] if len(arr) != i + 1 else None) for i in range(0, len(arr), 2)]


if __name__ == '__main__':
    print t(list('abcdef'))
    print t(list('abc'))

    print t2(list('abcdef'))
    print t2(list('abc'))
# -*- coding: utf-8 -*-


# def sort_fun1():
#     result = []
#     with open('./shoes.txt', 'r') as f:
#
#         for line in f.readlines():
#             l = line.rsplit()
#             result.append({
#                 'brand': ' '.join(l[0:-2]),
#                 'color': l[-2],
#                 'size': l[-1]})
#     result.sort(key=lambda x: x['size'])
#     result.sort(key=lambda x: x['brand'])
#     result.sort(key=lambda x: x['color'])
#     for i in result:
#         print i


def sort_fun():
    result = []
    with open('./shoes.txt', 'r') as file:
        for line in file:
            l = line.split(None, 2)
            result.append({'brand': l[0], 'color': l[1], 'size': l[2].strip()})

    result.sort(key=lambda x: x['size'])
    result.sort(key=lambda x: x['brand'])
    result.sort(key=lambda x: x['color'])
    for i in result:
        print i


if __name__ == '__main__':
    sort_fun()

shoes.txt

Adidas  orange  43
Nike    black   41
Adidas  black   39
New Balance pink    41
Nike    white   44
New Balance orange  38
Nike    pink    44
Adidas  pink    44
New Balance orange  39
New Balance black   43
New Balance orange  44

dict

  • get()
  • keys()/values()/items()
  • pop()
  • update()
  • clear()

except

try:
    <等待检测的代码>
except <异常名>:
    <处理异常语句>
except <异常名> as <数据>:
    <处理异常语句>
else:
    <没有产生异常执行的语句>
finally:
    <始终会执行的语句>

file

文件对象:

f = open('abc.txt')

文件属性:

f.name # 文件名
f.mode # modes: r, w, a, r+, binary

读取文件内容:

f.read() # get the file
f.read(100) # read 100 bytes
f.readline() # read one line
f.readlines() # read all lines
f.seek(0) # start of file

写入文件:

f.write(“some_content”)

关闭文件:

f.close()
f.flush()

函数式编程

  • map(), filter(), list comprehension
  • reduce(), lambda
  • dict comprehension
  • set comprehension

面向对象编程

魔法属性:

  • init
  • getattr
  • setattr
  • getitem
  • setitem
  • add
  • eq
  • contains
  • str
  • len
  • class
  • doc
  • repr
  • eq
  • gt

完毕。