python之路函数
1、函数参数,引用
2、lambda表达式
lambda表达式
f1 = lambda a1,a2: a1+a2
3、python的内置函数
abs(),绝对值
all(),循环参数,如果每个元素都为真,那么all返回值为真
0是假的,None 是假,“”,[],(),{},空值都是假的
any() 只要有一个是真则为真
ascii(对象),去对象的类中找_repr_,获取返回值
bin(),二进制
oct(),八进制
int(),十进制
hex(),十六进制
bool(), 判断真假,把一个对象转换成bool值,None,“”,【】,{}
bytes 字节
bytearray 字节列表
字节转字符串
bytes(“xxx”, encoding=‘utf-8’)
chr(),把数字转换成asc码,对应的字符
ord(),把字符转化成数字
实例:生成一个随机验证码
#!/usr/bin/env python
# -*- coding: utf-8 -*- import random temp = ""
for i in range(6):
# 生成0-4的随机数
num = random.randrange(0, 4)
# 如果随机数是1或3,那么就在验证码中生成一个0-9的随机数字
# 否则,验证码中生成一个随机字母
if num == 3 or num == 1:
rad2 = random.randrange(0, 10)
temp = temp + str(rad2)
else:
rad1 = random.randrange(65, 91)
c1 = chr(rad1)
temp = temp + rad1
print(temp)
验证码代码
callable(),能不能执行
compile(),编译
complex(),
dir(),看看函数提供的功能
divmod(),计算需要多少页
eval(),可以执行一个字符串形式的字符串,有返回值
exec(),执行python代码
一、 map(函数,可迭代的对象),让所有的数统一做个操作
li = [11, 22, 33] new_list = map(lambda a: a + 100, li)
li = [11, 22, 33]
sl = [1, 2, 3]
new_list = map(lambda a, b: a + b, li, sl)
二、filter(函数,可迭代的对象),过滤,循环可迭代的对象,获取每一个参数,
li = [11, 22, 33] new_list = filter(lambda arg: arg > 22, li) #filter第一个参数为空,将获取原来序列
li = [11, 22, 33] result = reduce(lambda arg1, arg2: arg1 + arg2, li) # reduce的第一个参数,函数必须要有两个参数
# reduce的第二个参数,要循环的序列
# reduce的第三个参数,初始值
format()字符串格式化
globals()获取所有的全局变量
locals()获取所有的局部变量
hash()算哈希值
isinstance(),判断某个对象是否有某个类创建的
issubclass(),是不是子类
open()打开文件
pow(),求指数
repr()====ascii(),
round()四舍五入
silce(),去对象的索引
vars()一个对象有的变量
字符串不能排序
#!/usr/bin/env python
# -*- coding: utf-8 -*- li = [1, 2, 22, 333, 444]
new_li = sorted(li)
print(new_li)
文件操作
一、打开文件
open(文件名,模式,编码)
默认是只读模式
打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。
打开文件的模式有:
- r,只读模式(默认)。
- w,只写模式。【不可读;不存在则创建;存在则删除内容;】
- a,追加模式。【可读; 不存在则创建;存在则只追加内容;】
"+" 表示可以同时读写某个文件
- r+,可读写文件。【可读;可写;可追加】
- w+,写读
- a+,同a
"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)
- rU
- r+U
"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
- rb
- wb
- ab
以字节的方式打开
1、只读 rb
二、操作文件
class file(object): def close(self): # real signature unknown; restored from __doc__
关闭文件
"""
close() -> None or (perhaps) an integer. Close the file. Sets data attribute .closed to True. A closed file cannot be used for
further I/O operations. close() may be called more than once without
error. Some kinds of file objects (for example, opened by popen())
may return an exit status upon closing.
""" def fileno(self): # real signature unknown; restored from __doc__
文件描述符
"""
fileno() -> integer "file descriptor". This is needed for lower-level file interfaces, such os.read().
"""
return 0 def flush(self): # real signature unknown; restored from __doc__
刷新文件内部缓冲区
""" flush() -> None. Flush the internal I/O buffer. """
pass def isatty(self): # real signature unknown; restored from __doc__
判断文件是否是同意tty设备
""" isatty() -> true or false. True if the file is connected to a tty device. """
return False def next(self): # real signature unknown; restored from __doc__
获取下一行数据,不存在,则报错
""" x.next() -> the next value, or raise StopIteration """
pass def read(self, size=None): # real signature unknown; restored from __doc__
读取指定字节数据
"""
read([size]) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached.
Notice that when in non-blocking mode, less data than what was requested
may be returned, even if no size parameter was given.
"""
pass def readinto(self): # real signature unknown; restored from __doc__
读取到缓冲区,不要用,将被遗弃
""" readinto() -> Undocumented. Don't use this; it may go away. """
pass def readline(self, size=None): # real signature unknown; restored from __doc__
仅读取一行数据
"""
readline([size]) -> next line from the file, as a string. Retain newline. A non-negative size argument limits the maximum
number of bytes to return (an incomplete line may be returned then).
Return an empty string at EOF.
"""
pass def readlines(self, size=None): # real signature unknown; restored from __doc__
读取所有数据,并根据换行保存值列表
"""
readlines([size]) -> list of strings, each a line from the file. Call readline() repeatedly and return a list of the lines so read.
The optional size argument, if given, is an approximate bound on the
total number of bytes in the lines returned.
"""
return [] def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
指定文件中指针位置
"""
seek(offset[, whence]) -> None. Move to new file position. Argument offset is a byte count. Optional argument whence defaults to
0 (offset from start of file, offset should be >= 0); other values are 1
(move relative to current position, positive or negative), and 2 (move
relative to end of file, usually negative, although many platforms allow
seeking beyond the end of a file). If the file is opened in text mode,
only offsets returned by tell() are legal. Use of other offsets causes
undefined behavior.
Note that not all file objects are seekable.
"""
pass def tell(self): # real signature unknown; restored from __doc__
获取当前指针位置
""" tell() -> current file position, an integer (may be a long integer). """
pass def truncate(self, size=None): # real signature unknown; restored from __doc__
截断数据,仅保留指定之前数据
"""
truncate([size]) -> None. Truncate the file to at most size bytes. Size defaults to the current file position, as returned by tell().
"""
pass def write(self, p_str): # real signature unknown; restored from __doc__
写内容
"""
write(str) -> None. Write string str to file. Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written.
"""
pass def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
将一个字符串列表写入文件
"""
writelines(sequence_of_strings) -> None. Write the strings to the file. Note that newlines are not added. The sequence can be any iterable object
producing strings. This is equivalent to calling write() for each string.
"""
pass def xreadlines(self): # real signature unknown; restored from __doc__
可用于逐行读取文件,非全部
"""
xreadlines() -> returns self. For backward compatibility. File objects now include the performance
optimizations previously implemented in the xreadlines module.
"""
pass
‘
f.tell()# 获取指针的位置
f.seek(num)#调整指针的位置
truncate()截取数据,仅保留指定之前的数据
要掌握的内容
三、关闭文件
with open('log','r') as f: ...
自动关闭
with支持同时打开两个文件
python之路函数的更多相关文章
- Python之路-函数
一.函数是什么: python中函数定义:函数是逻辑结构化和过程化的一种编程方法.定义函数的方法为: def function(): ""The function definiti ...
- python之路——函数进阶
阅读目录 楔子 命名空间和作用域 函数嵌套及作用域链 函数名的本质 闭包 本章小结 楔子 假如有一个函数,实现返回两个数中的较大值: def my_max(x,y): m = x if x> ...
- 百万年薪python之路 -- 函数的动态参数
1.函数的动态参数 1.1 动态接收位置参数 在参数位置用*表示接受任意参数 def eat(*args): print('我想吃',args) eat('蒸羊羔','蒸熊掌','蒸鹿尾儿','烧花鸭 ...
- Python之路-函数基础&局部变量与全局变量&匿名函数&递归函数&高阶函数
一.函数的定义与调用 函数:组织好的.可重复使用的.用户实现单一或者关联功能的代码段.函数能够提高应用的模块性和代码的重复利用率.Python提供了很多内置的函数,比如len等等,另外也可以根据自己的 ...
- 百万年薪python之路 -- 函数名的第一类对象及使用
函数名是一个变量, 但它是一个特殊的变量, 与括号配合可以执行函数的变量 1.1.函数名的内存地址 def func(): print("呵呵") print(func) 结果: ...
- 百万年薪python之路 -- 函数的动态参数练习
1.继续整理函数相关知识点. 2.写函数,接收n个数字,求这些参数数字的和.(动态传参) def func(*args,**kwargs): num_sum = 0 num_dic = [] num ...
- 百万年薪python之路 -- 函数初始
1.函数 1.1 认识函数 定义一个事情或者是功能,等到需要的时候直接去用就好了.那么这里定义东西就是一个函数 函数:对代码块和功能的封装和定义 函数的好处: 减少代码的重复性 代码可读性高 将功能进 ...
- 百万年薪python之路 -- 函数初始练习
1.整理函数相关知识点 2.写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者. def func(lst): lst = lst[1::2] return l ...
- 09-Python之路---函数进阶
Python之路---函数进阶️ 程序员三大美德: 懒惰 因为一直致力于减少工作的总工作量. 缺乏耐性 因为一旦让你去做本该计算机完成的事,你将会怒不可遏. 傲慢 因为被荣誉感冲晕头的你会把程序写得让 ...
随机推荐
- 使用scrapy框架爬取图片网全站图片(二十多万张),并打包成exe可执行文件
目标网站:https://www.mn52.com/ 本文代码已上传至git和百度网盘,链接分享在文末 网站概览 目标,使用scrapy框架抓取全部图片并分类保存到本地. 1.创建scrapy项目 s ...
- windows系统安装python
1.python3 下载 官网下载:https://www.python.org百度网盘下载:https://pan.baidu.com/s/1dH0UZg_7Q-YcppR0PjUfzQ提取码:xl ...
- float浮动以及案例演示
浮动元素会影响后边的元素,但不会影响前边的元素 清除浮动: 方法一:在浮动元素后面添加一个空元素 <!DOCTYPE html> <html lang="en"& ...
- 安装ubuntu到移动硬盘(UEFI+GPT),实现在别的电脑也可以使用(详细教程)
前置说明:博主小白,第一次安装ubuntu,参考了网上很多人的教程,发博记录一下自己的安装过程.由于有些地方博主理解较浅或者因为机器硬件等各方面原因,本教程适用有限,仅供参考. 1.准备工作 win系 ...
- 第二章.学习halcon的准备工作
*图片读取 read_image (Test1, 'C:/Users/Administrator/Desktop/new/Test1.jpg') *文件夹读取 list_files ('C:/User ...
- 【转】为什么使用length获取Java数组的长度
记得vamcily 曾问我:“为什么获取数组的长度用.length(成员变量的形式),而获取String的长度用.length()(成员方法的形式)?” 我当时一听,觉得问得很有道理.做同样一件事情, ...
- job无法自动运行基于ABP后台服务 - 后台作业和后台工人
原因: 后台作业和后台工人仅在你的应用程序运行的时候才工作.如果web应用长时间没有被请求执行,Asp.Net应用默认是关闭的 解决方案: 应用程序池(Application Pool),Proces ...
- linux服务基础之nginx配置详解
nginx简单介绍:https://www.cnblogs.com/ckh2014/p/10848670.html nginx编译安装:https://www.cnblogs.com/ckh2014/ ...
- JS绑定事件处理函数及处理流程
一.事件绑定的几种方式: 1.1 ele.on+“事件名“:如div.onclick = function(event){ }; 1.1.1这种方式兼容性非常好,但一个元素的同一个事件上只能绑定一个处 ...
- LeetCode 第二题 Add Two Numbers 大整数加法 高精度加法 链表
题意 You are given two non-empty linked lists representing two non-negative integers. The digits are s ...