常用python用法小记

生成器genration

参考 https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014317799226173f45ce40636141b6abc8424e12b5fb27000

如果一个函数定义中包含yield关键字,那么这个函数就不再是一个普通函数,而是一个generator;

在执行过程中,遇到yield就中断,返回,再次执行时从上次返回的yield语句处继续执行;

把函数改成generator后,我们基本上从来不会用next()来获取下一个返回值,而是直接使用for循环来迭代:

def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a + b
        n = n + 1
    return 'done'
    
 for n in fib(6):
     print(n)

index

出现某个值的下标。
eg. a=[4,5,6] 则a.index(5)=1。a.index(value,[start,stop])

pop(N)

可以用于数组,每次取出一个值,到下一个值,这样就不用i,然后i=i+1的操作了。
eg. a=[4,5,6,1,2,3] 则a.pop(0),输出4,a变为[5,6,1,2,3],之后再a.pop(0),输出5,a变为[6,1,2,3],a.pop(1),输出1,a变为[6,2,3]

remove 移除特定值

a = [1,1,2,3]

a.remove(2)     # a = [1,1,3]

a.remove(1)     # a = [1,3]

初始化一个固定大小的数组

a = [None]*N`一维数组

multilist = [[0 for col in range(5)] for row in range(3)]

a = np.zeros((M,N))`创建一个M*N的全0矩阵

创建二维矩阵(list):

twolist = [[0 for col in range(cols)] for row in range(rows)]
#cols、rows替换成行、列的具体数字,比如
twolist = [[0 for col in range(5)] for row in range(5)]   #5*5

python中的hashmap:就是dict

d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
d['Michael']     #会返回95

判断key是否存在:

'Michael' in d 
#返回True,判断是否在d中。可用来查重复,利用上哈希表的功能。 

初始化一个dict:

dict = {}

dict中根据value值取对应的key值:

def get_keys(d, value):
    return [k for k,v in d.items() if v == value]
    
get_keys({'a':'001', 'b':'002'}, '001') # => ['a']

替换 replace

s = s.replace(' ','%20')   #用%20替换空格

交换两个数

不需要swap,直接

t1,t2 = t2,t1

去重 用set

a='abbc'    #str格式 abbc
b=list(a)   #b是list格式 ['a','b','b','c']
c = list(set(b))    #set去重,再输出list格式 ['a','b',c']

join 需要把list串成字符串时使用

b = ['a', 'b', 'b', 'c']

d = ''.join(b)  #''中间填入连接符号 out:'abbc'  【常用】[单个char可以用,string不可用]
e = '-'.join(b) #out:'a-b-b-c'

list中为字符串时的合并成str:

str1 = ''     

seq = ['There','is','a','book']     #list型

str1 = ' '.join(seq)   #'There is a book'  #一个空格,用空格串起来

把数字列表转为数字 转化为一串数字

a = [1,2,3,45,67]

int(''.join([str(t) for t in a]))

input()使用

从键盘连续输入一个数组,并用空格隔开

num = [int(n) for n in input().split()]

从键盘连续输入一个数组,并用,隔开

num = [int(n) for n in input().split(',')]

从键盘输入几个变量, 并用空格隔开

n,m,p = map(int,input().split())
或者直接:
n,m=[int(i) for i in input().split()]

append、insert、extend

a.append是在末尾添加,每次只能添加一项(一项可以是一个dict);insert是在任意位置都可以添加

a = [5,4,2]

a.append(3)     #a = [5,4,2,3]

a.insert(0,1)   #a = [1,5,4,2,3]

想要一次添加很多项:

b = [0,1,2,3]

a += b  # a = a + 某[] 

常有题目,遍历完了,要把把b剩余项添加到a末尾:

a += b[j:]

extend

extend在改变里头元素,外头不会跟着一起改变(而append就会改变)

a = [1,2,3]

c = []

c.append(a)     # c = [[1,2,3]]

此时 a.append(4)    # a = [1,2,3,4],  c变为c=c = [[1,2,3,4]]!

用extend就不随元素改变。

d = []

1). d.extend(a)     # d = [[1,2,3]]

此时 a.append(4)    # a = [1,2,3,4],  a的元素改变了

# d = [[1,2,3]] 保持不变

2). d.extend([a])   # 则a的元素改变,d的元素也会跟着改变

int型整数拆成一个个单独数字

a = 123
#想分别提取1,2,3,用a%10,a/10%10,a/10/10%10的方法很麻烦
#直接:
a = str(a)  #a=123  (str型) a[0]='1'
a = list(map(int, a))  # 让每个元素分别变成int型,再保存成数组
#所以,可以汇总成:
a = list(map(int, str(a)))  # out: [1,2,3]

enumerate 生成下标

for x, y in enumerate(['a', 'b', 'c']):
print(x, y)

0 a
1 b
2 c

sort

变成struct结构,也想要按其中某一项,某个属性排序,类似《笔试题 汇总》中的按能力值排序,python的做法如下:

s=[['a',1],['c',3],['d',2]] #按第二个属性排序

s = sorted(s, key=lambda ss: ss[1])

在编程题中,写为:

a =[]        
for i in range(2):
    a.append([n for n in input().split(',')])   #input输入
a = sorted(a, key=lambda ss: ss[1])         #排序
# print(a)
sort的参数解释:

python2中:sorted(iterable[,cmp,[,key[,reverse=True]]])

作用:返回一个经过排序的列表。

第一个参数是一个iterable,返回值是一个对iterable中元素进行排序后的列表(list)。

可选的参数有三个,cmp、key和reverse。

  1. cmp指定一个定制的比较函数,这个函数接收两个参数(iterable的元素),如果第一个参数小于第二个参数,返回一个负数;如果第一个参数等于第二个参数,返回零;如果第一个参数大于第二个参数,返回一个正数。默认值为None。

  2. key指定一个接收一个参数的函数,这个函数用于从每个元素中提取一个用于比较的关键字。默认值为None。

  3. reverse是一个布尔值。如果设置为True,列表元素将被倒序排列。
    key参数的值应该是一个函数,这个函数接收一个参数并且返回一个用于比较的关键字。对复杂对象的比较通常是使用对象的切片作为关键字。例如:

    students = [(‘john’, ‘A’, 15), (‘jane’, ‘B’, 12), (‘dave’, ‘B’, 10)]
    sorted(students, key=lambda s: s[2]) #按年龄排序
    # [(‘dave’, ‘B’, 10), (‘jane’, ‘B’, 12), (‘john’, ‘A’, 15)]

python3中:sorted(iterable,/,*,key=None,reverse=False)
没有了cmp,但也有相似的:

from functools import cmp_to_key

nums = [1, 3, 2, 4]
nums.sort(key=cmp_to_key(lambda a, b: a - b))
print(nums)  # [1, 2, 3, 4]

一维向量变成多维矩阵

用法:

matrix = [list(matrix[col * i:col * i + col]) for i in range(row)]

eg.
matrix = 'abcesfcsadee'

matrix = [list(matrix[col * i:col * i + col]) for i in range(row)]  

# matrix = [['a', 'b', 'c', 'e'], ['s', 'f', 'c', 's'], ['a', 'd', 'e', 'e']]

递归注意变量不会返回

class Solution:
    def hasPath(self, matrix):
        a = 2
        def dis(matrix,a):
            for i in matrix:
                if a == i:
                    a=1 #a这里变成1,递归后,不会再变成2了!!!
                    dis(matrix[1:],a)
        dis(matrix,a)


a = Solution().hasPath([1,2,3])
print(a)  

牛客网 python规范

https://www.nowcoder.com/discuss/276

import sys 
for line in sys.stdin:
    a = line.split()
    print(int(a[0]) + int(a[1]))

global

a = 5
 
def test():
    global a
 #此处声明,告诉执行引擎:我要用全局变量a,不要整成局部的了!
    a = 1
    print 'In test func: a = %d' % a
 
test()
print 'Global a = %d' % a
运行结果:
In test func: a = 1
Global a = 1
a = 5 

不加global:

def test():
    a = 1
    print 'In test func: a = %d' % a
test()
print 'Global a = %d' % a
运行结果:
In test func: a = 1
Global a = 5
可以看出,不加global的时候,在函数内部是改不了外面的全局变量的(list类型例外)。

复制

a=[1,2,3]
b=a #令b=a
b[1] = 1 #此时b=[1,1,2],a=[1,1,2],a的值也变了!
#要想让a的值不变的方法:
b = a[:] 

list复制时采用b=a[:]

init()和__call__()函数

init():等同于类的构造函数(同理,del()等同于类的析构函数)。因此,init()方法的作用是创建一个类的实例。

call():def call(self, *args),Python中的函数的引用可以作为输入传递到其他的函数/方法中,并在其中被执行。x.call(1,2)等同于调用x(1,2)。这个实例本身在这里相当于一个函数。

  1. init()的作用是初始化某个类的一个实例。
  2. call()的作用是使实例能够像函数一样被调用,同时不影响实例本身的生命周期(call()不影响一个实例的构造和析构)。但是__call__()可以用来改变实例的内部成员的值。

举例:

class X(object):
    def __init__(self, a, b, range):
        self.a = a
        self.b = b
        self.range = range
    def __call__(self, a, b):
        self.a = a
        self.b = b
        print('__call__ with ({}, {})'.format(self.a, self.b))
    def __del__(self, a, b, range):
        del self.a
        del self.b
        del self.range
        
>>> xInstance = X(1, 2, 3)
>>> xInstance(1,2)
__call__ with (1, 2)

python在linux下的调试工具 pdb

import pdb

# 在需要设置断点的地方加入
pdb.set_trace()

pdb的常用命令说明: 

l #查看运行到哪行代码 
n #单步运行,跳过函数 
s #单步运行,可进入函数 
p 变量 #查看变量值 
b 行号 #断点设置到第几行 
b #显示所有断点列表 
cl 断点号 #删除某个断点 
cl #删除所有断点 
c #跳到下一个断点 
r #return当前函数 
exit #退出

执行python -m pdb test.py

tf.app.flags.FLAGS

命令行执行程序时,需要传些参数

import tensorflow as tf

tf.app.flags.DEFINE_string('recipe', 'aaa', 'The directory containing the recipe') # 第一个参数 是方法名,第二个是默认值,第三个是对方法的说明(不会传入)
 
FLAGS = tf.app.flags.FLAGS  #对象实例

flag_recipe = FLAGS.recipe  # print(flag_recipe) 为aaa(默认设的值)。

# 比如这个py文件名叫a.py,执行 python a.py --recipe='abcde',则flag_recipe = 'abcde'

逐行读取两个文本文件

from itertools import izip

with open("textfile1") as textfile1, open("textfile2") as textfile2: 
    for x, y in izip(textfile1, textfile2):
        x = x.strip()
        y = y.strip()
        print("{0}\t{1}".format(x, y))

在Python 3中,使用内置的zip替换itertools.izip。

input输入的字符串转化为表达式并计算出结果 python3输入表达式

加eval():

print(eval(input()))

>>> 1+2+(3*4) 15

用python2直接就是出来结果了。

{0} 占位符

“2 + 2 = {0}”.format(4) 希望{0}被format里的第一个索引替换

比如 {0} {1}.format(1,2),同理:1,2替换{0}和{1}

assert

assert condition

用来让程序测试这个condition,如果condition为false,那么raise一个AssertionError出来。逻辑上等同于:

if not condition:
    raise AssertionError()

举例:

>>> assert 1==1
>>> assert 1==0
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    assert 1==0
AssertionError
>>> assert True
>>> assert False
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    assert False
AssertionError
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值