0
点赞
收藏
分享

微信扫一扫

PythonNote001---Tricks of Python


记录Python中常用的一些函数,备查

1 打印当前目录

import os
os.getcwd()

'/Users/liudong/There is no end to learning/[05]Learning_Python/[01]Foundation/Note of Python/[04]Tricks of Python/Code'

2 查看帮助

  1. help(os.getcwd) 可以帮助我们了解该对象的更多信息
  2. dir(os.getcwd) 可以帮助我们获取该对象的大部分相关属性
  3. os.getcwd.doc为模块、类、函数等添加说明性的文字,使程序易读易懂,更重要的是可以通过Python自带的标准方法将这些描述性文字信息输出,前后各两个下划线

help(os.getcwd)

Help on built-in function getcwd in module posix:

getcwd()
Return a unicode string representing the current working directory.

dir(os.getcwd)

['__call__',
'__class__',
'__delattr__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__module__',
'__name__',
'__ne__',
'__new__',
'__qualname__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__self__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__text_signature__']

## 和help返回结果相同
print(os.getcwd.__doc__)

Return a unicode string representing the current working directory.

3 列表

3.1 列表元素个数统计

## 统计所有元素个数
listA = ["A","B","C","A"]
len(listA)

4

## 统计某个元素的个数
listA.count("A")

2

## 列表增加元素
x = [1,2,3]
x.extend([4,3,2,1])
print(x)

[1, 2, 3, 4, 3, 2, 1]

3.2 集合运算

## 交集
listA = ["A","B","C"]
listB = ["A","B","C","D"]
list(set(listA).intersection(set(listB)))
## 或者
set(listA)&set(listB)

{'A', 'B', 'C'}

## 并集
list(set(listA).union(set(listB)))

['B', 'A', 'D', 'C']

## 差集,在B中不在A中
list(set(listB).difference(set(listA)))

['D']

3.3 列表的逆序

## 两种方式:是否改变原来列表
## 下面reverse的翻转方式会改变原来list的排序
x=[1,2,3];y=[1,2,3]
x1=x[::-1];y.reverse()
print("now x is %s "%x);
print("x1 is %s"%x1);
print("y is %s"%y)

now x is [1, 2, 3] 
x1 is [3, 2, 1]
y is [3, 2, 1]

列表排序

## sorted不改变列表本身排序
## 可以通过赋值操作,完成排序
x=[3,2,1]
x1=sorted(x)

## sort改变列表本身排序
## 排序后的数据直接覆盖原列表
y=[3,2,1]
y.sort()
y1=y
print("sorted x is %s"%x);
print("x1 is %s"%x1);
print("sorted y is %s"%y);
print("y1 is %s"%y1)

sorted x is [3, 2, 1]
x1 is [1, 2, 3]
sorted y is [1, 2, 3]
y1 is [1, 2, 3]

4 字符串

4.1 字符串截取

## 等间隔截取
x='0123456789'
print(x[2:8:2])# start =2 stop=10,step=2
print(x[::3]) ## start=beginning,stop=end,sep=3

246
0369

5 字典

## 取出所有的key,或者所有value
x={'1':'a','2':'b','3':'c'}
print(list(x.keys()))
print(list(x.values()))

['1', '2', '3']
['a', 'b', 'c']

6 赋值符号的说明

## x,y同时绑定[1,2,3],改变x,y中一个列表的元素,内存地址id为91576392的值发生改变
x=[1,2,3]
y=x
y[0]=3
print("x is %s and id is %s"%(x,id(x)))
print("y is %s and id is %s"%(y,id(y)))

x is [3, 2, 3] and id is 4571010056
y is [3, 2, 3] and id is 4571010056

7 添加模块调用路径

## 调用函数或者模块时,需要先添加相应的路径
import sys
import_path = "./app/python/shandaixia/stragety"
if import_path not in sys.path:
sys.path.append(import_path)

8 文件内建函数(open)

8.1 open的基本用法

  基本用法​​file_object = open(file,mode = 'r')​​ 参数含义:

  1. file_name要打开的文件名字的字符串,可以是相对路径或者是绝对路径
  2. access_mode文件打开的模型:"r"读取;"w"写入,且为从开头覆盖;"a"结尾追加
  3. 其余参数参看帮助文档

8.2 文件的写入

  使用open函数,新建文本文件,进行写入操作。

## 进行读写操作
f = open(file = 'test.txt',mode = 'w')## 该文件不存在,写入模式自动生成文件
f.write("line1 \nline2 \nline3") ## \n换行符号
f.close() ## 关闭文件对象

## 追加文本
f = open(file = 'test.txt',mode = 'a')## 该文件不存在,写入模式自动生成文件
f.write("\nline4") ## \n换行符号
f.close() ## 关闭文件对象

8.3 文件的读取

  文件内容读取函数主要分为​​read​​​、​​readline​​​、​​readlines​​​。其中​​read​​​直接读取所有字节到字符串中,​​readline​​​读取一行数据到字符串中,​​readlines​​读取所有行数据到列表中,列表中每个元素代表每一行的所有字节。

f = open(file = 'test.txt',mode = 'r')## 读取文件
read_txt = f.read()
print(read_txt)
f.close()

line1 
line2
line3
line4

## 每一次读取都从上一步后面读取
f = open(file = 'test.txt',mode = 'r')## 读取文件
readline_txt1 = f.readline()
readline_txt2 = f.readline()
readline_txt3 = f.readline()
readline_txt4 = f.readline()
print(readline_txt1)
print(readline_txt2)
print(readline_txt3)
print(readline_txt4)
f.close()

line1 

line2

line3

line4

f = open(file = 'test.txt',mode = 'r')## 读取文件
readlines_txt = f.readlines()
print(readlines_txt)
f.close()

['line1 \n', 'line2 \n', 'line3\n', 'line4']

9 找到目录下类似的文件

import glob
glob.glob('*.ip*')

['Tricks of Python.ipynb']

10 变量的永久储存

import pickle
f = open('somedata', 'wb')#二进制打开 ,没有该文件,新建
pickle.dump([1, 2, 3, 4], f)# 储存列表
f.close() # 关闭文件
f = open('somedata', 'rb') # 打开文件
x = pickle.load(f) # 输出变量

[1, 2, 3, 4]

11 向量化的ifelse

print('this is True')  if 1 == 1 else print('this is False')

this is True

12 isinstance

判断数据’123’是不是(str,int,list)中的某一个类型

isinstance ('123',(str,int,list))

True


举报

相关推荐

0 条评论