python 自学笔记

参数

import sys
print(sys.argv)
# 执行结果
#  PS C:\laoban\python_notes\test> py test.py ii
# ['test.py', 'ii']
# 使用时需要先判断用户有没有传入参数,再获取参数

转义字符 "\"

# 如果需要忽略字符串中所有转义字符,则加上"r"
print(r'C:\some\name')

字符串切片

>>> word = 'Python'
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'
// 切片的开始总是被包括在结果中,而结束不被包括

列表

  • 列表切片
>>> squares = [1, 4, 9, 16, 25]
>>> squares[:]
[1, 4, 9, 16, 25]
// 切片赋值
>>> letters[2:5] = ['C', 'D', 'E']
  • 循环时可以利用enumerate同时取出索引
  • 利用zip 同时循环两个列表
for i, v in enumerate(['tic', 'tac', 'toe']):
     print(i, v)
for q, a in zip(questions, answers):
     print('What is your {0}?  It is {1}.'.format(q, a))
  • 其他
len( list ) # 长度
del list[2] # 删除
[1, 2, 3] + [4, 5, 6] # 拼接
['Hi!'] * 4 # 重复
3 in [1, 2, 3] # 是否存在
max(list) or min(list) # 最大最小值
list.append(obj) # 添加新元素
list.count(obj)# 元素出现次数
list.index(x[, start[, end]]) # 查找元素位置,start end 为选填
list.remove(obj)# 移除匹配项
list.pop( -1 )  # 移除项,默认索引-1
list.sort() # 排序,可选正反序
list.copy()   # 复制列表,类似于 a[:] (浅复制)

while循环

  • 普通循环
while a < 10:
    print(a)
    a, b = b, a+b  # 用逗号分隔 多个赋值
  • 无限循环
i = 1
while 1:            # 循环条件为1必定成立
    print i         # 输出1~10
    i += 1
    if i > 10:     # 当i大于10时跳出循环
        break    # continue 
  • while else 循环
while count < 5:
   print count, " is  less than 5"
   count = count + 1
else: # 相当于在跳出循环后,执行一次else
   print count, " is not less than 5"

if

 if x < 0:
     x = 0
     print('Negative changed to zero')
 elif x == 0:
     print('Zero')

for 遍历迭代

words = ['cat', 'window', 'defenestrate']
for w in words:
     print(w, len(w))
  • range() 生成数字列表
for i in range(5):
     print(i)
  • 逆向遍历
for i in reversed(range(1, 10, 2)):
     print(i)

pass 占位符 (循环或def中是不允许为空的)

定义函数

# 必须后跟函数名称和带括号的形式参数列表。构成函数体的语句从下一行开始,并且必须缩进。
def fib(n = 666):    
     pass
  • 重要警告
    默认值只会执行一次。这条规则在默认值为可变对象(列表、字典以及大多数类实例)时很重要。比如,下面的函数会存储在后续调用中传递给它的参数:
def f(a, L=[]):
    L.append(a)
    return L
print(f(1))
print(f(2))
print(f(3))
# 打印
# [1]
# [1, 2]
# [1, 2, 3]
  • 关键字参数
# (*name 必须出现在 **name 之前。) 
# *arguments接收所有的位置参数
# **keywords接收所有的关键字参数
def cheeseshop(kind, *arguments, **keywords):
    pass
  • Lambda 匿名函数
# Lambda 相当于普通函数的语法糖
# 限于单行表达式
def make_incrementor(n):
     return lambda x: x + n

列表推导式

  • map
# 类似简写,map第一个参数为方法 ,第二个为列表,遍历列表中每个值去调用方法,返回调用后组成的新列表
squares = list(map(lambda x: x**2, range(10)))
  • 列表推导式
squares = [x**2 for x in range(10)]
  • 嵌套列表推导式
matrix = [
     [1, 2, 3, 4],
     [5, 6, 7, 8],
     [9, 10, 11, 12],
 ]
>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

del 删除切片或变量,非清空

>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]

元组('a', 'b', 'c') tuple

# 创建元组(元组不可变,仅能通过索引获取,或解包)
t = 12345, 54321, 'hello!'
singleton = 'hello',  
# 元组解包
x, y, z = t

集合 (相当于数学中的集合)

集合是由不重复元素组成的无序的集。它的基本用法包括成员检测和消除重复元素。集合对象也支持像 联合,交集,差集,对称差分等数学运算。
花括号或 set() 函数可以用来创建集合,要创建一个空集合你只能用 set() 而不能用 {}

basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}

字典dict 键值对

# 以键索引,键必须为不可变的值
tel = {'jack': 4098, 'sape': 4139}
  • 字典的循环 items
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items():
   print(k, v)

|| && !

not  # !
or  # ||
and  # &&
in 和 not in # 判断在不在
is 和 is not  #判断是不是(可变对象判断指针,不判断内容)

模块

模块是一个包含Python定义和语句的文件, 例如: test.py

import fibo # 导入模块
fibo.fib(1000) # 使用模块 
from fibo import fib, fib2  # 直接导入模块内部的方法 
import fibo as fib  # 导入模块后改名

sys.path

内置模块,用于设置导入模块的路径

import sys
sys.path.append('/ufs/guido/lib/python')

内置函数 dir() 用于查找模块定义的名称,返回指定模块内部所有定义的方法与变量

输入输出

  • F 或 f
# 引号前加f可以使用{变量名}的写法
f'Results of the {year} {event}'
'Results of the 2016 Referendum'
  • str()

用于返回人类可读的值的表示

  • {phone:10d}

用于插值中变量名后加冒号可以设置输出时的字符宽度

  • format()

用于替换字符串中的插值
'We are the {} who say "{}!"'.format('knights', 'Ni')

读写文件open()

f = open('workfile', 'w')
# 读取文件最好使用with 关键字,当读取完成后文件会被正确关闭
with open('workfile') as f:
     read_data = f.read()

f.readline() 读取一行,再次执行读取下一行
f.write('This is a test\n') 写入文字

  • JSON 解压缩
import json
json.dumps([1, 'simple', 'list'])
x = json.load(f)

处理异常

for arg in sys.argv[1:]:
    try:
        f = open(arg, 'r')
    except OSError:
        print('cannot open', arg)
    else:
        print(arg, 'has', len(f.readlines()), 'lines')
        f.close()
    finally:
        pass

global与nonlocal

global关键字修饰变量后标识该变量是全局变量,对该变量进行修改就是修改全局变量,而nonlocal关键字修饰变量后标识该变量是上一级函数中的局部变量,如果上一级函数中不存在该局部变量,nonlocal位置会发生错误(最上层的函数使用nonlocal修饰变量必定会报错)。

  • 属性引用类
class MyClass:
    """A simple example class"""
    i = 12345

    def f(self):
        return 'hello world'
  • 类的 实例化
class Complex:
     def __init__(self, realpart, imagpart):
         self.r = realpart
         self.__i = imagpart  # 变量名前加两个下划线为私有变量

type()

全局对象,用于判断对象类型

dir()

全局对象,用于获得一个str对象的所有属性和方法

你可能感兴趣的:(python 自学笔记)