1、函数参数(引用)  函数的传参,传的是引用

def func(args):args.appand(123)
li=[11,22,33]
func(li)
print(li)
[11,22,33,123]

2、lambda表达式

f4(函数名)=lambda  参数:reture值

3、内置函数

 1、dict() 创建字典、 list() 创建列表  、str()创建字符串、   tuple()创建元祖、 floot()浮点、   input()等待用户输入、

  round()四舍五入、len()计算长度(除整数)、max()取最大值、 min()取最小值、 print()打印、type()查看类型、 

  reversed()反转、 sum(可迭代的对象)求和、range()循环但不输出、

2、abs()  取绝对值

a=abs(-2)
print(a)
2

3、all()循环参数,如果每个元素都为真,则返回True,只要有一个元素为假,则返回False

  If the iterable is empty, return True

 如果all里面只有一个空,则为真

4、any()循环参数,只要有一个元素为真,则返回True

   If the iterable is empty, return False

如果any里面只有一个空,则为假

5、ascii()  去输入的元素的类中找__repr__方法,获取其返回值

li=[]
a=ascii(li)
print(a)
[]

 6、bin(数字)  二进制表示

a=bin(6)
print(a)
0b110

 7、oct()   八进制表示

a=oct(6)
print(a)
0o6

 8、int()  十进制表示

a=int(6)
print(a)
6

 9、hex()十六进制表示

a=hex(6)
print(a)
0x6

 10、各种进制之间的转换

其他进制相互转只有一种方式  oct(其他进制)  

其他的相互转换有俩种方式  int(其他进制数字)或 int(“其他进制数字”,base=进制)

>>> oct(x)

>>> hex(x)

>>> bin(x)

>>> int(x)

>>>int(x,base=x)

a=hex(6)
print(a)
b=int("0x6",base=16)
print(b)
0x6
6

11、bool() 判断真假,把一个对象转换成布尔值

布尔值为False: [], {}、(), "" , 0, None

a=bool("")
print(a)
False

12、 bytes()  字节       bytearray()   字节列表

字符串和字节之间的转换

#字符串转字节
a=bytes("中国人",encoding="utf-8")
print(a)
b'\xe4\xb8\xad\xe5\x9b\xbd\xe4\xba\xba'#字节转字符串
b=str(a,encoding="utf-8")
print(b)
中国人

13、chr()  将传入的数字转换成ascii中所对应的元素

a=chr(66)
print(a)
B

14、ord()  将传入的元素转换成ascii中对应的数字

a=ord("a")
print(a)
97

15、random   一个模块,可以随机产生一个元素

import random
a=random.randrange(65,90)
print(a)

16、验证码

import random
b=""
for i in range(6):c=random.randrange(0,4)if c==1 or c==3:d=random.randrange(0,9)b=b+str(d)else:a=random.randrange(65,80)b=b+chr(a)
print(b)

17、callable()  检查产生可否被执行,可执行返回True,否则返回False

def  f1()reture 123
a=callable(f1)print(a)
True

18、dir()  查看对象类中的方法   help()

a=dic(str())
print(a)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', 

19、divmod() 用于运算俩个数的除法,并把商和余数放到元祖中

a=divmod(10,3)
print(a)
(3, 1)

20、eval()  可以执行一个字符串形式的表达式(字符串里面只能是数字)

a="1+2"
b=eval(a)
print(b)
3

b=eval("a+2",{"a":1})   #eval后可以接收参数(字典),用来申明变量
print(b)
3

21、exec() 用于执行.py代码

exec("for i in range(4):print(i)")
0
1
2
3

22、filter(函数,可迭代的)  将可迭代的每一个参数传入函数中,如果返回True 则输出参数,反之则过滤掉

def z(a):if a>3:return Trueelse:return False
ret=filter(z,[1,2,3,4,5,])
print(ret)
for i in ret:print(i)
<filter object at 0x0000001EA85B9550>    #此处相当于range()  不直接输出浪费内存
4
5

def z(a):return a+12
ret=filter(z,[1,2,3,4,5,])
print(ret)
for i in ret:print(i)
<filter object at 0x0000000F9EE49550>
1
2
3
4
5

23、map(函数,可迭代的)  将可迭代的每一个参数传入函数中,执行函数体中的运算,并将运算值输出

def z(a):return a+12
ret=map(z,[1,2,3,4,5,])
print(ret)
for i in ret:print(i)
<map object at 0x00000082DC909550>
13
14
15
16
17

 24、frozenset()  一个冻结的set,不可添加元素

 25、global() 获取全局变量,并可以改变全局变量,locals() 获取局部变量

def z():name="123"print(globals())print(locals())
z()
{'z': <function z at 0x000000751D4EAC80}
{'name': '123'}

 26、hash() 用于保存优化字典里面的k值

dict={"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq":1}
a=hash("qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq")
print(a)
936761249792483134

27、isinstannce()   判断是否是同一个类

li=list()
r=isinstance(li,list)
print(r)
True

28、iter() 创建一个可以迭代的对象,迭代的对象执行next时,取下一个值

a=iter([1,2,3])
print(a)
b1=next(a)
print(b1)
b2=next(a)
print(b2)
b3=next(a)
print(b3)
<list_iterator object at 0x0000005D5C239550>
1
2
3

 29、pow() 求幂

a=pow(2,10)
print(a)
1024

 30、zip() 将多个可迭代的类型,按照索引位置一一对应组合起来

a=[1,2,3,4]
b=[5,6,7,8]
c=(1,2,3,4)
d=zip(a,b,c)
print(d)
for i in d:print(i)
<zip object at 0x000000DB794F0E88>
(1, 5, 1)
(2, 6, 2)
(3, 7, 3)
(4, 8, 4)

 **31、sorted()为对象(都是同一种类型)排序,得到新值

a=[1,2,3,4,1212,13,4,56,7]
b=a.sort()      #执行sort方法
print(a)
[1, 2, 3, 4, 4, 7, 13, 56, 1212]

  1>数字排序

a=[1,2,3,4,1212,13,4,56,7]
b=sorted(a)    #执行sort方法得到新值
print(b)
[1, 2, 3, 4, 4, 7, 13, 56, 1212]

 2>字符串排序

char=['赵',"123", "1", "25", "65","679999999999","a","B","alex","c" ,"A", "_", "ᒲ",'a钱','孙','李',"余", '佘',"佗", "㽙", "铱", "钲钲㽙㽙㽙"]new_chat = sorted(char)
print(new_chat)
for i in new_chat:print(bytes(i, encoding='utf-8'))
['1', '123', '25', '65', '679999999999', 'A', 'B', '_', 'a', 'alex', 'a钱', 'c', 'ᒲ', '㽙', '佗', '佘', '余', '孙', '李', '赵', '钲钲㽙㽙㽙', '铱']
b'1'
b'123'
b'25'
b'65'          b'679999999999'    #字符串中是数字的按数字大小排序(从左边第一位开始)
b'A'
b'B'
b'_'
b'a'
b'alex'
b'a\xe9\x92\xb1'
b'c'          #大写的字母排到前面,小写的在后面,再看第一位(左边第一位)
b'\xe1\x92\xb2'
b'\xe3\xbd\x99'
b'\xe4\xbd\x97'
b'\xe4\xbd\x98'
b'\xe4\xbd\x99'
b'\xe5\xad\x99'
b'\xe6\x9d\x8e'
b'\xe8\xb5\xb5'
b'\xe9\x92\xb2\xe9\x92\xb2\xe3\xbd\x99\xe3\xbd\x99\xe3\xbd\x99'
b'\xe9\x93\xb1'   #数字按照xe后跟的先排

 ***open()函数     用于处理文件

文件句柄 = open('文件路径', '模式')

打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作

打开文件的模式有:

  基本操作

  普通打开()

  a=open("111.py","r",encoding="utf-8")    python 以r方式打开的时候把必须注明编码方式(文本中有汉字的情况)

  • r ,只读模式【默认】
  • w,只写模式【不可读;不存在则创建;存在则清空内容;】
  • x, 只写模式【不可读;不存在则创建,存在则报错】
  • a, 追加模式【不可读;   不存在则创建;存在则只追加内容;

"b"表示以字节的方式操作

  • rb  或 r+b
  • wb 或 w+b
  • xb 或 w+b
  • ab 或 a+b

"+" 表示可以同时读写某个文件

  • r+, 读写【可读,可写】
  • w+,写读【可读,可写】
  • x+ ,写读【可读,可写】
  • a+, 写读【可读,可写】

  seek(参数)   用于调整指针位置

  tell()        用于获取指针位置

  read(参数)加参数用于读前几个字符

r+   表示可读,可写

先读后写:能读到全部内容,指针移动到最后面,在内容后面追加内容(无论read(参数)中参数是几,后面再写的话指针都是在最后,但再读得话是按照前面读以后指针的位置作为起点)————————关闭文件前

a=open("334.txt","r+" ,encoding="utf-8")
b=a.read()
a.write("fgh")
a.close()
print(b)
123

先写后读:指针在开始位置,写入的内容把以前的覆盖掉,指针移动到写完后的位置,读取到写完后的内容

a=open("334.txt","r+",encoding="utf-8")
a.write("fgh")
c=a.read()
a.close()
print(c)

w+  先清空,再写之后指针在末端,利用seek(参数)调整指针位置就可以读了

a=open("334.txt","w+")
print(a.tell())
a.write("asd")
a.seek(0)
b=a.read()
a.close()
print(b)

x+  同w+,如果文件存在则报错

a+  打开的同时指针移动到最后

先读后写:一开始指针再最后读取不到内容

先写后读:在内容后面追加内容,调整指针位置可以读取到内容

操作

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 forfurther I/O operations.  close() may be called more than once withouterror.  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. """passdef isatty(self): # real signature unknown; restored from __doc__判断文件是否是同意tty设备""" isatty() -> true or false.  True if the file is connected to a tty device. """return Falsedef next(self): # real signature unknown; restored from __doc__获取下一行数据,不存在,则报错""" x.next() -> the next value, or raise StopIteration """passdef 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 requestedmay be returned, even if no size parameter was given."""passdef readinto(self): # real signature unknown; restored from __doc__读取到缓冲区,不要用,将被遗弃""" readinto() -> Undocumented.  Don't use this; it may go away. """passdef 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 maximumnumber of bytes to return (an incomplete line may be returned then).Return an empty string at EOF."""passdef 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 thetotal 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
(offset from start of file, offset should be >= 0); other values are 1(move relative to current position, positive or negative), and 2 (moverelative to end of file, usually negative, although many platforms allowseeking 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 causesundefined behavior.Note that not all file objects are seekable."""passdef tell(self): # real signature unknown; restored from __doc__获取当前指针位置""" tell() -> current file position, an integer (may be a long integer). """passdef 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()."""passdef 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 beforethe file on disk reflects the data written."""passdef 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 objectproducing strings. This is equivalent to calling write() for each string."""passdef xreadlines(self): # real signature unknown; restored from __doc__可用于逐行读取文件,非全部"""xreadlines() -> returns self.For backward compatibility. File objects now include the performanceoptimizations previously implemented in the xreadlines module."""pass

class TextIOWrapper(_TextIOBase):"""Character and line based layer over a BufferedIOBase object, buffer.encoding gives the name of the encoding that the stream will bedecoded or encoded with. It defaults to locale.getpreferredencoding(False).errors determines the strictness of encoding and decoding (seehelp(codecs.Codec) or the documentation for codecs.register) anddefaults to "strict".newline controls how line endings are handled. It can be None, '','\n', '\r', and '\r\n'.  It works as follows:* On input, if newline is None, universal newlines mode isenabled. Lines in the input can end in '\n', '\r', or '\r\n', andthese are translated into '\n' before being returned to thecaller. If it is '', universal newline mode is enabled, but lineendings are returned to the caller untranslated. If it has any ofthe other legal values, input lines are only terminated by the givenstring, and the line ending is returned to the caller untranslated.* On output, if newline is None, any '\n' characters written aretranslated to the system default line separator, os.linesep. Ifnewline is '' or '\n', no translation takes place. If newline is anyof the other legal values, any '\n' characters written are translatedto the given string.If line_buffering is True, a call to flush is implied when a call towrite contains a newline character."""def close(self, *args, **kwargs): # real signature unknown关闭文件passdef fileno(self, *args, **kwargs): # real signature unknown文件描述符  passdef flush(self, *args, **kwargs): # real signature unknown刷新文件内部缓冲区passdef isatty(self, *args, **kwargs): # real signature unknown判断文件是否是同意tty设备passdef read(self, *args, **kwargs): # real signature unknown读取指定字节数据passdef readable(self, *args, **kwargs): # real signature unknown是否可读passdef readline(self, *args, **kwargs): # real signature unknown仅读取一行数据passdef seek(self, *args, **kwargs): # real signature unknown指定文件中指针位置passdef seekable(self, *args, **kwargs): # real signature unknown指针是否可操作passdef tell(self, *args, **kwargs): # real signature unknown获取指针位置passdef truncate(self, *args, **kwargs): # real signature unknown截断数据,仅保留指定之前数据passdef writable(self, *args, **kwargs): # real signature unknown是否可写passdef write(self, *args, **kwargs): # real signature unknown写内容passdef __getstate__(self, *args, **kwargs): # real signature unknownpassdef __init__(self, *args, **kwargs): # real signature unknownpass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object.  See help(type) for accurate signature. """passdef __next__(self, *args, **kwargs): # real signature unknown""" Implement next(self). """passdef __repr__(self, *args, **kwargs): # real signature unknown""" Return repr(self). """passbuffer = property(lambda self: object(), lambda self, v: None, lambda self: None)  # defaultclosed = property(lambda self: object(), lambda self, v: None, lambda self: None)  # defaultencoding = property(lambda self: object(), lambda self, v: None, lambda self: None)  # defaulterrors = property(lambda self: object(), lambda self, v: None, lambda self: None)  # defaultline_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None)  # defaultname = property(lambda self: object(), lambda self, v: None, lambda self: None)  # defaultnewlines = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default_CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default_finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

flush(self): 刷新文件内部缓冲区

  如果进程没有结束(用input(“ssss”)),write(“assds”)的内容就没有刷到硬盘中,读取不出来,加上福禄寿flush()就能够强制把内容刷到硬盘,不结束进程也能读取到

read(参数):

  没有加参数读取所有内容,加上参数表示读取几个字符(以r方式打开)或几个字节(以rb方式打开)

readline():仅读取一行数据

truncate(self, *args, **kwargs): 截断数据,仅保留指定之前数据  依赖于指针的位置
a=open("334.txt","r+")
print(a.tell())
print(a.seek(5))
a.truncate()
a.close() 0 5        #用于截取文件内容中前五个字符串的内容

f=open("111.py',"r+",encoding="utf-8")  #f是可以循环的for  line  in  f:print(line)      #可以把内容一行一行的读出来,可以看到内容的最后一行

管理上下文

  为了避免打开文件后忘记关闭,可以通过管理上下文,即:

with  open("xxx","xx",encoding="utf-8") as f:pass

  如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

  在Python 2.7 及以后,with又支持同时对多个文件的上下文进行管理,即:

with open('log1') as obj1, open('log2') as obj2:pass

转载于:https://www.cnblogs.com/luxiaojun/p/5475711.html

python基础(set)补充相关推荐

  1. 十一. Python基础(11)—补充: 作用域 装饰器

    十一. Python基础(11)-补充: 作用域 & 装饰器 1 ● Python的作用域补遗 在C/C++等语言中, if语句等控制结构(control structure)会产生新的作用域 ...

  2. Python基础数据类型补充及深浅拷贝

    本节主要内容: 1. 基础数据类型补充 2. set集合 3. 深浅拷贝 主要内容: 一. 基础数据类型补充 首先关于int和str在之前的学习中已经讲了80%以上了. 所以剩下的自己看一看就可以了. ...

  3. 万恶之源 - Python基础知识补充

    编码转换 编码回顾: 1. ASCII : 最早的编码. ⾥⾯有英⽂⼤写字⺟, ⼩写字⺟, 数字, ⼀些特殊字符. 没有中⽂, 8个01代码, 8个bit, 1个byte 2. GBK: 中⽂国标码, ...

  4. Python基础之补充1

    1.三元运算 三元运算(三目运算),是对简单的条件语句的缩写. 1 2 3 result = 值1 if 条件 else 值2    # 如果条件成立,那么将 "值1" 赋值给re ...

  5. python基础知识补充

    文章目录 1. jupyter notebook 解释 2. ipython 魔法命令 3. latex in Markdown cell(在markdown里面编写数学公式) 4. jupyter ...

  6. python容量变化类型有哪些_python基础数据类型补充以及编码的进阶

    一. 基础数据类型补充内容 1.1 字符串 字符串咱们之前已经讲了一些非常重要的方法,剩下还有一些方法虽然不是那么重要,但是也算是比较常用,在此给大家在补充一些,需要大家尽量记住. #captaliz ...

  7. [转载] python创建集合、计算a|b_python之路(集合,深浅copy,基础数据补充)

    参考链接: Python 集合set | symmetric_difference 一.集合:类似列表,元组的存储数据容器,不同点是不可修改,不可重复.无序排列. 1.创建集合: (1).set1 = ...

  8. Python基础知识笔记——补充

    其实之前已经学过很多python基础了,甚至学了好多遍了,但最近报名了一个线上班,有空会看看一些视频,因此在本文补充一些以前漏学或者老师讲得不错的知识. 目录 Hash模块 简介 Base64 zli ...

  9. Python之基础数据补充、set集合和深浅拷贝

    基础数据补充 字符串的常用操作         1. join() li = ["李嘉诚", "麻花藤", "⻩海峰", "刘嘉玲 ...

  10. 从列表中切片最佳英雄组合,我的选择是亚索和李青——补充python基础语法有关数字类型和列表的知识

    本文继续补充个人对python基础语法的理解,这里主要讲数字类型和列表~ 目前还不算初级程序员把,但是一洗头就掉头发,现在都不敢洗头了~ 数字类型 python中的数字类型:int(整型).float ...

最新文章

  1. 通过eclipse调试MapReduce任务
  2. cmake CMakeLists.txt 命令 add_compile_options、add_definitions、target_compile_definitions、build_command
  3. python学起来难不难-Python为什么那么受欢迎?学习Python难不难?
  4. HTTP状态码(HTTP Status Code),常见的error 404, error 504等的意思
  5. 为什么ABAP整型的1转成string之后,后面会多个空格
  6. ipython和python怎么用_如何使用IPython重新加载和自动加载?
  7. h3c 虚拟服务器 下一跳,H3CNE 312题和313题 直连路由静态路由的下一跳问题
  8. 解析浏览器访问服务器 Servlet 应用程序的交互过程(Servlet 容器如何处理请求资源路径)
  9. 前端基础-CSS的各种选择器的特点以及CSS的三大特性
  10. IDEA 热部署 仅支持jdk1.6,1.7
  11. Activiti工作流引擎的使用
  12. Adaboost原理和实例
  13. java类和对象的基础(笔记)
  14. 【机房重构】组合查询--存储过程
  15. Appium使用教程_Android篇
  16. Quartz在QRTZ_JOB_DETAILS表中存储了什么
  17. Java开发知识点!mysql运行sql文件很慢
  18. UML软件建模技术-基于IBM RSA工具的基础实训
  19. java避免出现科学计数法表示_Java中的浮点数-科学计数法-加减乘除
  20. explain用法和结果的含义

热门文章

  1. cpu核心 线程 进程_科个普:进程、线程、并发、并行
  2. 清除tomcat缓存
  3. java jackson_Jackson 框架的高阶应用
  4. 获取所有task_Asp.Net Core 轻松学-多线程之Task快速上手
  5. ubuntu上安装python3.7教程_Ubuntu安装python 3. 7
  6. 大数据分析项目成功的五项基本原则
  7. mysql5.6主从不报错_mysql5.6.26主从复制报错1050
  8. html重复div绘制,[DIV+CSS]绘制2重交叉表_html/css_WEB-ITnose
  9. 人脸检测(十二)--DDFD算法
  10. 关于OpenCV使用遇到的问题集(多数为转载)