Python 官網: python 前沿.可惜是英文原版.所以,我要練習英文閱讀.🧐🧐" rel="noopener noreferrer">https://www.python.org/
自學並不是什麼神秘的東西,一個人一輩子自學的時間總是比在學校學習的時間長,沒有老師的時候總是比有老師的時候多.
—— 華羅庚
One-line loading code
print(''.join(chr(int(''.join(i), 16)) for i in zip(*[iter('576f772c2049276d2077726974696e6720696e2068657861646563696d616c21')]*2)))
Run這行代碼,The following sentence will be output.我感覺好神奇!決定Study……
仔細“研究”、拆分後,發現是zip()Works on the same iterator,產生的Magic(魔法).This makes me want to be right againiter()“鑽研”了一番.
先看看iter()的“文檔”:
print(iter.__doc__)
iter(iterable) -> iterator
iter(callable, sentinel) -> iterator
Get an iterator from an object. In the first form, the argument must supply its own iterator, or be a sequence.
In the second form, the callable is called until it returns the sentinel.
“文檔”顯示:iter()There is one parameter given、給定兩個參數,兩種用法.
一、iter(iterable) -> iterator
When only one parameter is given,參數必須是可迭代對象(iterable object),Return that parameter(iterable object)的iterator(迭代器).換句話說,就是iter()賦予了iterable objectContents can be returned one by one(元素)的能力,就是讓iterable object具有了__next__()“魔法”方法.可以用內置函數next()實現,Can also use itself“新”得技能(next()方法)實現.iterable objectParameters can be eligible“任意”Python對象.如:
/sdcard/qpython $ python
Python 3.10.2 (main, Mar 1 2022, 12:58:06) [Clang 12.0.8 (https://android.googlesource.com/toolchain/llvm-project c935d99d7 on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> iter('ok')
<str_iterator object at 0x79d5ca4460>
>>> iter([3, 4])
<list_iterator object at 0x79d5c21c90>
>>> iter((6, 'c'))
<tuple_iterator object at 0x79d5c5aa70>
>>> iter({
3,9})
<set_iterator object at 0x79d5ca3a80>
>>> iter({
5: 6, 'ok': 'haha'})
<dict_keyiterator object at 0x79d5c36700>
>>>>
如您所見,Iterators returned by various objects,All keep their own“烙印”.字符串、列表、元組、集合、字典key,這Python五大基礎類型,All have their own stamps.這對“她”作為迭代器使用,毫無阻滯.Now let's practice:
>>> iter('ok').__next__()
'o'
>>> iter([3, 4]).__next__()
3
>>> iter((6, 'c')).__next__()
6
>>> iter(('c', 9)).__next__()
'c'
>>> iter({
3, 9}).__next__()
9
>>> d = iter({
5: 6, 'ok': 'haha'})
>>> d.__next__()
5
>>> d.__next__()
'ok'
>>>
an iterator,Can be changed.
Python3.x內置函數zip()、map()返回的就是iterator.如:
>>> z = zip((4, 6), list('Good'))
>>> z
<zip object at 0x78cffa1380>
>>> z.__next__()
(4, 'G')
>>> z.__next__()
(6, 'o')
>>> z.__next__()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> m = map(str, range(6, 9))
>>> m
<map object at 0x78cff99de0>
>>> next(m, 'The end.')
'6'
>>> next(m, 'The end.')
'7'
>>> next(m, 'The end.')
'8'
>>> next(m, 'The end.')
'The end.'
>>>
由前面“操作”可以看出,zip object、map object她就是iterator,她們有__next__()方法,內置函數next()也可以調用.
>>> next(zip((4,), ['d']))
(4, 'd')
>>> map(int, list('456')).__next__()
4
iter(object)配合zip()的“特殊”用法
iter()借助zip()和*星號“聯眾”之力,The fixed-length sequence selection can be achieved with concise code.例:
為簡化例子,First define a functionmychoice(iterator, num).
>>> def mychoice(iterator, num):
... ''' iterator -> 迭代器對象 ... num -> int,The number of consecutive values '''
... return zip(*[iterator]*num)
...
>>> print(*mychoice(iter(range(9)), 2))
(0, 1) (2, 3) (4, 5) (6, 7)
>>> print(*mychoice(iter('Chongqing'), 3))
('C', 'h', 'o') ('n', 'g', 'q') ('i', 'n', 'g')
>>>
神不神奇,驚不驚喜.這,It is mentioned at the beginning of this note“裝逼代碼”的“奇妙”用法.You may have found out,由於zip()的特性,Can't exactly match grouped sequence elements,被捨棄.For example, to restore hexadecimal encoded characters,Four or two digits have no remainder,所以對“實際”的應用,幾乎沒有影響.這,How is it achieved?I think it is based on迭代器“只可以讀取一次”的特性,在iter()The official documentation did not find the relevant instructions.因為我在這裡zip()的參數,are all the same iterator,Repeating the iterator several times is to continuously fetch several sequence elements.
上面的return 語句,也可以寫成
return zip(iterator, ierator, ...) # If you want to take several sequence elements in a row, repeat it several times.
舉個粟子:
>>>
>>> iterator = iter('I love you.')
>>> tem = iterator
>>> print(*zip(tem, tem, tem))
('I', ' ', 'l') ('o', 'v', 'e') (' ', 'y', 'o')
>>>
to the same iterator,在zip()The parameters are repeated three times,This completes the selection of three consecutive characters.
利用這一“特性”,可以“異想天開”do something.例如:Revert the hexadecimal character encoding to “本來的樣子”.
s = 'I am Chongqing“夢幻精靈_cq”,我愛Python,is studying A funny hexadecimal statement.'
en = "Wow, I'm writing in hexadecimal!"
hex_s = '576F772C2049276D2077726974696E6720696E2068657861646563696D616C21'
def to_hex(s, num=2):
''' Convert characters to hexadecimal encoding,\nThe characters contain Chinesenum=4,\nThe default is pure English. '''
return ''.join(map(lambda x: hex(ord(x))[2:].upper().zfill(num), s)) # Convert character encoding and strip hexadecimal identification characters stored with set bits,不足位補“0”.Seamless mosaic characters,返回字符串.
if __name__== '__main__':
print(f"\n原字符串:{
s}\n十六進制:\n{
to_hex(s, 4)}") # Save character encoding with four hexadecimal characters.
print(f"\n原字符串:{
en}\n十六進制:\n{
to_hex(en)}") # 用to_hex()The default parameter converts English characters into2位十六進制ASCII編碼.
b = zip(*[iter(to_hex(s, 4))]*4) # Convert characters to hexadecimal character encoding.
print(f"\nHex-encoded string:\n{
[''.join(i) for i in b]}\n") # Print a hexadecimal character-encoded string.
b = zip(*[iter(to_hex(s, 4))]*4) # Convert characters to hexadecimal character encoding.
for i in b: # Traverse the reverting characters.
print(chr(int(''.join(i), 16)), end="")
Output screenshots
on the iterator variableb的操作中,Why is it assigned twice.因為bWhen printing a list of hexadecimal character encodings,已讀取b所以再對bThe operation must be assigned first.(iterator只可以讀取一次.)
It can also be seen that the restoration is done with only one compound statement,或者轉換 -> Restore the entire process.不過,“較長”的復合語句“Jerky and hard to read”,除了“裝逼”,Use sparingly.
print(f"\n\n{
''.join([chr(int(''.join(i), 16)) for i in zip(*[iter(hex_s)]*2)])}")
print(f"\n{
''.join(map(lambda x: chr(int(''.join(x),16)), zip(*[iter(to_hex(s,4))]*4)))}\n")
Output screenshots
二、iter(iterable, sentinel) -> iterator
If the second argument is givensentinel,第一個參數必須是可調用對象(A function or class method that takes no arguments,And each call will return a value),The first parameter is called in a loop,直到==第二參數(sentinel的值).正如sentinelthe same interpretation,就是——“哨兵”——到此為止.不返回sentinel的值.如:
or more information.
>>> lis = range(9)
>>> iterator = iter(lis)
>>> tem = iter(iterator.__next__, 7)
>>> tem
<callable_iterator object at 0x78d0163940>
>>> print(*tem)
0 1 2 3 4 5 6
>>>
>>> iterator = iter('I am Dream elf, I live in Chongqing.')
>>> print(iter(iterator.__next__, ','))
<callable_iterator object at 0x78d01638b0>
>>> print(*iter(iterator.__next__, ','))
I a m D r e a m e l f
when the second parametersentinel是7時,Just output the one in front of her0~6,不輸出7;當sentinel是“,”,Just output the first half of the string,without output“,”.
iter()官方文檔:
文檔鏈接https://docs.python.org/3/library/functions.html#iter
文檔內容,
iter(object[, sentinel])
Return an iterator object. The first argument(參數) is interpreted very differently depending on the presence of the second argument. Without a second argument, object must be a collection object which supports the iterable protocol (the iter() method), or it must support the sequence protocol (the getitem() method with integer arguments starting at 0). If it does not support either of those protocols, TypeError is raised. If the second argument, sentinel, is given, then object must be a callable object. The iterator created in this case will call object with no arguments for each call to its next() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.
See also Iterator Types.
One useful application of the second form of iter() is to build a block-reader. For example, reading fixed-width blocks from a binary database file until the end of file is reached:
from functools import partial
with open(‘mydata.db’, ‘rb’) as f:
for block in iter(partial(f.read, 64), b’'):
process_block(block)
參考CSDN博文:
來源:老齊教室
全棧領域優質創作者——寒佬(還是國內某高校學生)好文:《非技術文—關於英語和如何正確的提問》,“英語”和“會提問”是學習的兩大利器.
【8大編程語言的適用領域】先別著急選語言學編程,先看它們能干嘛
靠譜程序員的好習慣