零基礎自學python,python基礎(set)補充

 2023-12-06 阅读 36 评论 0

摘要: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、函數參數(引用)??函數的傳參,傳的是引用

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

?2、lambda表達式

f4(函數名)=lambda??參數:reture值

3、內置函數

零基礎自學python,

?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

python set集合、  If the iterable is empty, return True

 如果all里面只有一個空,則為真

?

?4、any()循環參數,只要有一個元素為真,則返回True

 ? If the iterable is empty, return False

??? 如果any里面只有一個空,則為假

random python?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、各種進制之間的轉換

python sort、其他進制相互轉只有一種方式? oct(其他進制)??

其他的相互轉換有倆種方式? int(其他進制數字)或 int(“其他進制數字”,base=進制)

>>> oct(x)

>>> hex(x)

>>> bin(x)

?

python join,>>> 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)
中國人

python list?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__', 

python有什么用。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

python3??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

Python set、?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('文件路徑', '模式')

?打開文件時,需要指定文件路徑和以何等方式打開文件,打開后,即可獲取該文件句柄,日后通過此文件句柄對該文件操作

python tuple?打開文件的模式有:

  基本操作

  普通打開()

  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+, 寫讀【可讀,可寫】

python編程100例。  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)

python中set()函數的用法??

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

python set用法。?

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

?

python自學。轉載于:https://www.cnblogs.com/luxiaojun/p/5475711.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/2/192167.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息