zip、izip、izip_longest的區別


  昨兒,小爺在LeetCode上刷了一道題,關於把兩個字符串型的整數加和的問題(當然不能直接強轉),鏈接在這https://leetcode.com/problems/add-strings/,感興趣的朋友們可以一試,不難,只要想做肯定做得出,無非就是要想想進位和哪個字符串位數多的問題,提交幾次考慮的情況就全面了。

  說來簡單,小爺還是做了兩個小時,沒刷過題真的是不行,短煉。

  小爺用的是Python,寫了百十來行,用了 一系列if,else。然而,當去欣賞大牛們的代碼時,沒想着優化,就是本着能做出來的態度的小爺我還是震驚了,人家就用了7行!!

  那么,對於小爺這樣一個好學的孩子,怎么能放過這樣一個學習的機會,在此記錄一下。

  主要就是zip、izip和izip_longest的用法。

  • zip(build-in方法)

文檔中這樣描述:

  This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence. 

  譯過來就是把多個序列或者是迭代器的元素,組合成元組。返回的元組的長度是所有輸入序列中最短的。

舉個栗子:

In [27]: a = ['a', 'b', 'c', 'd', 'e'] In [28]: b = range(10) In [29]: zip(a,b) Out[29]: [('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4)]
注意這里返回的是列表,且列表的長度依賴於輸入元組中較短的一個
  • izip

文檔中這樣描述:

  Make an iterator that aggregates elements from each of the iterables. Like zip() except that it returns an iterator instead of a list. Used for lock-step iteration over several iterables at a time. 

  把不同的迭代器的元素聚合到一個迭代器中。類似zip()方法,但是返回的是一個迭代器而不是一個list。 用於同步迭代幾個iterables。

如果輸入的兩個序列都是特別大的情況,zip就會很慢了。使用izip比較下。(因為返回的是一個迭代器,並且同步迭代,所以速度比較快。

In [30]: a = range(10000000) In [31]: b = range(10000000) In [32]: tim %%timeit %time %timeit In [32]: %timeit(zip(a,b)) 1 loops, best of 3: 811 ms per loop In [33]: import itertools In [34]: %timeit(itertools.izip(a,b)) 1000000 loops, best of 3: 349 ns per loop
  • izip_longest

文檔中這樣描述:

  Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted 

  也就是說這個zip方法使用izip一樣的原理,但是會使用最長的迭代器來作為返回值的長度,並且可以使用 fillvalue來制定那些缺失值的默認值

舉個栗子:

In [35]: a = ['a','b','c'] In [36]: b = range(10) In [37]: itertools.izip_longest(a,b,fillvalue=-1) Out[37]: <itertools.izip_longest at 0x250e540> In [38]: c = itertools.izip_longest(a,b,fillvalue=-1) In [42]: for i in c:  ....: print i  ....: ('a', 0) ('b', 1) ('c', 2) (-1, 3) (-1, 4) (-1, 5) (-1, 6) (-1, 7) (-1, 8) (-1, 9)

  此外,牛人的方法里還用了ord(),這個之前也沒見過,該函數和chr()對應,是將ascii字符轉換成對應的整數值,而chr()是將整數值轉換成對應的ascii字符。
舉個栗子:
>>> print chr(48), chr(49), chr(97)
0 1 a
 
        
>>> print ord('a'), ord('0'), ord('1')
97 48 49

  至此,牛人的方法就能理解了。
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM