{"id":6167,"date":"2017-02-10T15:43:29","date_gmt":"2017-02-10T07:43:29","guid":{"rendered":"https:\/\/kyle.ai\/blog\/?p=6167"},"modified":"2017-02-10T15:48:45","modified_gmt":"2017-02-10T07:48:45","slug":"python%e6%a0%87%e5%87%86%e5%ba%93%e4%b9%8bfunctoolsitertoolsoperator","status":"publish","type":"post","link":"https:\/\/kyle.ai\/blog\/6167.html","title":{"rendered":"Python\u6807\u51c6\u5e93\u4e4bfunctools\/itertools\/operator"},"content":{"rendered":"<h1>\u5f15\u8a00<\/h1>\n<p>functools, itertools, operator\u662fPython\u6807\u51c6\u5e93\u4e3a\u6211\u4eec\u63d0\u4f9b\u7684\u652f\u6301\u51fd\u6570\u5f0f\u7f16\u7a0b\u7684\u4e09\u5927\u6a21\u5757\uff0c\u5408\u7406\u7684\u4f7f\u7528\u8fd9\u4e09\u4e2a\u6a21\u5757\uff0c\u6211\u4eec\u53ef\u4ee5\u5199\u51fa\u66f4\u52a0\u7b80\u6d01\u53ef\u8bfb\u7684Pythonic\u4ee3\u7801\uff0c\u63a5\u4e0b\u6765\u6211\u4eec\u901a\u8fc7\u4e00\u4e9bexample\u6765\u4e86\u89e3\u4e09\u5927\u6a21\u5757\u7684\u4f7f\u7528\u3002<\/p>\n<h1>functools\u7684\u4f7f\u7528<\/h1>\n<p>functools\u662fPython\u4e2d\u5f88\u91cd\u8981\u7684\u6a21\u5757\uff0c\u5b83\u63d0\u4f9b\u4e86\u4e00\u4e9b\u975e\u5e38\u6709\u7528\u7684\u9ad8\u9636\u51fd\u6570\u3002\u9ad8\u9636\u51fd\u6570\u5c31\u662f\u8bf4\u4e00\u4e2a\u53ef\u4ee5\u63a5\u53d7\u51fd\u6570\u4f5c\u4e3a\u53c2\u6570\u6216\u8005\u4ee5\u51fd\u6570\u4f5c\u4e3a\u8fd4\u56de\u503c\u7684\u51fd\u6570\uff0c\u56e0\u4e3aPython\u4e2d\u51fd\u6570\u4e5f\u662f\u5bf9\u8c61\uff0c\u56e0\u6b64\u5f88\u5bb9\u6613\u652f\u6301\u8fd9\u6837\u7684\u51fd\u6570\u5f0f\u7279\u6027\u3002<\/p>\n<h1>partial<\/h1>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n&gt;&gt;&gt; from functools import partial\r\n&gt;&gt;&gt; basetwo = partial(int, base=2)\r\n&gt;&gt;&gt; basetwo('10010')\r\n18\r\n<\/pre>\n<p>basetwo(&#8216;10010&#8217;)\u5b9e\u9645\u4e0a\u7b49\u4ef7\u4e8e\u8c03\u7528int(&#8216;10010&#8217;, base=2)\uff0c\u5f53\u51fd\u6570\u7684\u53c2\u6570\u4e2a\u6570\u592a\u591a\u7684\u65f6\u5019\uff0c\u53ef\u4ee5\u901a\u8fc7\u4f7f\u7528functools.partial\u6765\u521b\u5efa\u4e00\u4e2a\u65b0\u7684\u51fd\u6570\u6765\u7b80\u5316\u903b\u8f91\u4ece\u800c\u589e\u5f3a\u4ee3\u7801\u7684\u53ef\u8bfb\u6027\uff0c\u800cpartial\u5185\u90e8\u5b9e\u9645\u4e0a\u5c31\u662f\u901a\u8fc7\u4e00\u4e2a\u7b80\u5355\u7684\u95ed\u5305\u6765\u5b9e\u73b0\u7684\u3002<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\ndef partial(func, *args, **keywords):\r\n    def newfunc(*fargs, **fkeywords):\r\n        newkeywords = keywords.copy()\r\n        newkeywords.update(fkeywords)\r\n        return func(*args, *fargs, **newkeywords)\r\n    newfunc.func = func\r\n    newfunc.args = args\r\n    newfunc.keywords = keywords\r\n    return newfunc\r\n<\/pre>\n<h1>partialmethod<\/h1>\n<p>partialmethod\u548cpartial\u7c7b\u4f3c\uff0c\u4f46\u662f\u5bf9\u4e8e\u7ed1\u5b9a\u4e00\u4e2a\u975e\u5bf9\u8c61\u81ea\u8eab\u7684\u65b9\u6cd5\u7684\u65f6\u5019\uff0c\u8fd9\u4e2a\u65f6\u5019\u5c31\u53ea\u80fd\u4f7f\u7528partialmethod\u4e86\uff0c\u6211\u4eec\u901a\u8fc7\u4e0b\u9762\u8fd9\u4e2a\u4f8b\u5b50\u6765\u770b\u4e00\u4e0b\u4e24\u8005\u7684\u5dee\u5f02\u3002<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nfrom functools import partial, partialmethod\r\ndef standalone(self, a=1, b=2):\r\n    &quot;Standalone function&quot;\r\n    print('  called standalone with:', (self, a, b))\r\n    if self is not None:\r\n        print('  self.attr =', self.attr)\r\nclass MyClass:\r\n    &quot;Demonstration class for functools&quot;\r\n    def __init__(self):\r\n        self.attr = 'instance attribute'\r\n    method1 = functools.partialmethod(standalone)  # \u4f7f\u7528partialmethod\r\n    method2 = functools.partial(standalone)  # \u4f7f\u7528partial\r\n<\/pre>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n&gt;&gt;&gt; o = MyClass()\r\n&gt;&gt;&gt; o.method1()\r\n  called standalone with: (&lt;__main__.MyClass object at 0x7f46d40cc550&gt;, 1, 2)\r\n  self.attr = instance attribute\r\n# \u4e0d\u80fd\u4f7f\u7528partial\r\n&gt;&gt;&gt; o.method2()\r\nTraceback (most recent call last):\r\n  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;\r\nTypeError: standalone() missing 1 required positional argument: 'self'\r\n<\/pre>\n<h1>singledispatch<\/h1>\n<p>\u867d\u7136Python\u4e0d\u652f\u6301\u540c\u540d\u65b9\u6cd5\u5141\u8bb8\u6709\u4e0d\u540c\u7684\u53c2\u6570\u7c7b\u578b\uff0c\u4f46\u662f\u6211\u4eec\u53ef\u4ee5\u501f\u7528singledispatch\u6765\u52a8\u6001\u6307\u5b9a\u76f8\u5e94\u7684\u65b9\u6cd5\u6240\u63a5\u6536\u7684\u53c2\u6570\u7c7b\u578b\uff0c\u800c\u4e0d\u7528\u628a\u53c2\u6570\u5224\u65ad\u653e\u5230\u65b9\u6cd5\u5185\u90e8\u53bb\u5224\u65ad\u4ece\u800c\u964d\u4f4e\u4ee3\u7801\u7684\u53ef\u8bfb\u6027\u3002<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nfrom functools import singledispatch\r\nclass TestClass(object):\r\n    @singledispatch\r\n    def test_method(arg, verbose=False):\r\n        if verbose:\r\n            print(&quot;Let me just say,&quot;, end=&quot; &quot;)\r\n        print(arg)\r\n    @test_method.register(int)\r\n    def _(arg):\r\n        print(&quot;Strength in numbers, eh?&quot;, end=&quot; &quot;)\r\n        print(arg)\r\n    @test_method.register(list)\r\n    def _(arg):\r\n        print(&quot;Enumerate this:&quot;)\r\n        for i, elem in enumerate(arg):\r\n            print(i, elem)\r\n<\/pre>\n<p>\u4e0b\u9762\u901a\u8fc7@test_method.register(int)\u548c@test_method.register(list)\u6307\u5b9a\u5f53test_method\u7684\u7b2c\u4e00\u4e2a\u53c2\u6570\u4e3aint\u6216\u8005list\u7684\u65f6\u5019\uff0c\u5206\u522b\u8c03\u7528\u4e0d\u540c\u7684\u65b9\u6cd5\u6765\u8fdb\u884c\u5904\u7406\u3002<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n&gt;&gt;&gt; TestClass.test_method(55555)  # call @test_method.register(int)\r\nStrength in numbers, eh? 55555\r\n&gt;&gt;&gt; TestClass.test_method(&#x5B;33, 22, 11])   # call @test_method.register(list)\r\nEnumerate this:\r\n0 33\r\n1 22\r\n2 11\r\n&gt;&gt;&gt; TestClass.test_method('hello world', verbose=True)  # call default\r\nLet me just say, hello world\r\n<\/pre>\n<h1>wraps<\/h1>\n<p>\u88c5\u9970\u5668\u4f1a\u9057\u5931\u88ab\u88c5\u9970\u51fd\u6570\u7684__name__\u548c__doc__\u7b49\u5c5e\u6027\uff0c\u53ef\u4ee5\u4f7f\u7528@wraps\u6765\u6062\u590d\u3002<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nfrom functools import wraps\r\ndef my_decorator(f):\r\n    @wraps(f)\r\n    def wrapper():\r\n        &quot;&quot;&quot;wrapper_doc&quot;&quot;&quot;\r\n        print('Calling decorated function')\r\n        return f()\r\n    return wrapper\r\n@my_decorator\r\ndef example():\r\n    &quot;&quot;&quot;example_doc&quot;&quot;&quot;\r\n    print('Called example function')\r\n<\/pre>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n&gt;&gt;&gt; example.__name__\r\n'example'\r\n&gt;&gt;&gt; example.__doc__\r\n'example_doc'\r\n# \u5c1d\u8bd5\u53bb\u6389@wraps(f)\u6765\u770b\u4e00\u4e0b\u8fd0\u884c\u7ed3\u679c\uff0cexample\u81ea\u8eab\u7684__name__\u548c__doc__\u90fd\u5df2\u7ecf\u4e27\u5931\u4e86\r\n&gt;&gt;&gt; example.__name__\r\n'wrapper'\r\n&gt;&gt;&gt; example.__doc__\r\n'wrapper_doc'\r\n<\/pre>\n<p>\u6211\u4eec\u4e5f\u53ef\u4ee5\u4f7f\u7528update_wrapper\u6765\u6539\u5199<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nfrom itertools import update_wrapper\r\ndef g():\r\n    ...\r\ng = update_wrapper(g, f)\r\n# equal to\r\n@wraps(f)\r\ndef g():\r\n    ...\r\n<\/pre>\n<p>@wraps\u5185\u90e8\u5b9e\u9645\u4e0a\u5c31\u662f\u57fa\u4e8eupdate_wrapper\u6765\u5b9e\u73b0\u7684\u3002<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\ndef wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES):\r\n    def decorator(wrapper):\r\n        return update_wrapper(wrapper, wrapped=wrapped...)\r\n    return decorator\r\n<\/pre>\n<h1>lru_cache<\/h1>\n<p>lru_cache\u548csingledispatch\u662f\u5f00\u53d1\u4e2d\u5e94\u7528\u975e\u5e38\u5e7f\u6cdb\u7684\u9ed1\u9b54\u6cd5\uff0c\u63a5\u4e0b\u6765\u6211\u4eec\u6765\u770b\u4e00\u4e0blru_cache\u3002\u5bf9\u4e8e\u91cd\u590d\u7684\u8ba1\u7b97\u6027\u4efb\u52a1\uff0c\u4f7f\u7528\u7f13\u5b58\u52a0\u901f\u662f\u975e\u5e38\u91cd\u8981\u7684\uff0c\u4e0b\u9762\u6211\u4eec\u901a\u8fc7\u4e00\u4e2afibonacci\u7684\u4f8b\u5b50\u6765\u770b\u4e00\u4e0b\u4f7f\u7528lru_cache\u4e0e\u4e0d\u4f7f\u7528lru_cache\u5728\u901f\u5ea6\u4e0a\u7684\u5dee\u5f02\u3002<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n# clockdeco.py\r\nimport time\r\nimport functools\r\ndef clock(func):\r\n    @functools.wraps(func)\r\n    def clocked(*args, **kwargs):\r\n        t0 = time.time()\r\n        result = func(*args, **kwargs)\r\n        elapsed = time.time() - t0\r\n        name = func.__name__\r\n        arg_lst = &#x5B;]\r\n        if args:\r\n            arg_lst.append(', '.join(repr(arg) for arg in args))\r\n        if kwargs:\r\n            pairs = &#x5B;'%s=%r' % (k, w) for k, w in sorted(kwargs.items())]\r\n            arg_lst.append(', '.join(pairs))\r\n        arg_str = ', '.join(arg_lst)\r\n        print('&#x5B;%0.8fs] %s(%s) -&gt; %r ' % (elapsed, name, arg_str, result))\r\n        return result\r\n    return clocked\r\n<\/pre>\n<p>\u4e0d\u4f7f\u7528lru_cache<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nfrom clockdeco import clock\r\n@clock\r\ndef fibonacci(n):\r\n    if n &lt; 2:\r\n        return n\r\n    return fibonacci(n-2) + fibonacci(n-1)\r\nif __name__=='__main__':\r\n    print(fibonacci(6))\r\n<\/pre>\n<p>\u4e0b\u9762\u662f\u8fd0\u884c\u7ed3\u679c\uff0c\u4ece\u8fd0\u884c\u7ed3\u679c\u53ef\u4ee5\u770b\u51fafibonacci(n)\u4f1a\u5728\u9012\u5f52\u7684\u65f6\u5019\u88ab\u91cd\u590d\u8ba1\u7b97\uff0c\u8fd9\u662f\u975e\u5e38\u8017\u65f6\u6d88\u8d39\u8d44\u6e90\u7684\u3002<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n&#x5B;0.00000119s] fibonacci(0) -&gt; 0 \r\n&#x5B;0.00000143s] fibonacci(1) -&gt; 1 \r\n&#x5B;0.00021172s] fibonacci(2) -&gt; 1 \r\n&#x5B;0.00000072s] fibonacci(1) -&gt; 1 \r\n&#x5B;0.00000095s] fibonacci(0) -&gt; 0 \r\n&#x5B;0.00000095s] fibonacci(1) -&gt; 1 \r\n&#x5B;0.00011444s] fibonacci(2) -&gt; 1 \r\n&#x5B;0.00022793s] fibonacci(3) -&gt; 2 \r\n&#x5B;0.00055265s] fibonacci(4) -&gt; 3 \r\n&#x5B;0.00000072s] fibonacci(1) -&gt; 1 \r\n&#x5B;0.00000072s] fibonacci(0) -&gt; 0 \r\n&#x5B;0.00000095s] fibonacci(1) -&gt; 1 \r\n&#x5B;0.00011158s] fibonacci(2) -&gt; 1 \r\n&#x5B;0.00022268s] fibonacci(3) -&gt; 2 \r\n&#x5B;0.00000095s] fibonacci(0) -&gt; 0 \r\n&#x5B;0.00000095s] fibonacci(1) -&gt; 1 \r\n&#x5B;0.00011349s] fibonacci(2) -&gt; 1 \r\n&#x5B;0.00000072s] fibonacci(1) -&gt; 1 \r\n&#x5B;0.00000095s] fibonacci(0) -&gt; 0 \r\n&#x5B;0.00000095s] fibonacci(1) -&gt; 1 \r\n&#x5B;0.00010705s] fibonacci(2) -&gt; 1 \r\n&#x5B;0.00021267s] fibonacci(3) -&gt; 2 \r\n&#x5B;0.00043225s] fibonacci(4) -&gt; 3 \r\n&#x5B;0.00076509s] fibonacci(5) -&gt; 5 \r\n&#x5B;0.00142813s] fibonacci(6) -&gt; 8 \r\n8\r\n<\/pre>\n<p>\u4f7f\u7528lru_cache<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nimport functools\r\nfrom clockdeco import clock\r\n@functools.lru_cache() # 1\r\n@clock # 2\r\ndef fibonacci(n):\r\n    if n &lt; 2:\r\n       return n\r\n    return fibonacci(n-2) + fibonacci(n-1)\r\nif __name__=='__main__':\r\n    print(fibonacci(6))\r\n<\/pre>\n<p>\u4e0b\u9762\u662f\u8fd0\u884c\u7ed3\u679c\uff0c\u5bf9\u4e8e\u5df2\u7ecf\u8ba1\u7b97\u51fa\u6765\u7684\u7ed3\u679c\u5c06\u5176\u653e\u5165\u7f13\u5b58\u3002<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n&#x5B;0.00000095s] fibonacci(0) -&gt; 0 \r\n&#x5B;0.00005770s] fibonacci(1) -&gt; 1 \r\n&#x5B;0.00015855s] fibonacci(2) -&gt; 1 \r\n&#x5B;0.00000286s] fibonacci(3) -&gt; 2 \r\n&#x5B;0.00021124s] fibonacci(4) -&gt; 3 \r\n&#x5B;0.00000191s] fibonacci(5) -&gt; 5 \r\n&#x5B;0.00024652s] fibonacci(6) -&gt; 8 \r\n8\r\n<\/pre>\n<p>\u4e0a\u9762\u6211\u4eec\u9009\u7528\u7684\u6570\u5b57\u8fd8\u4e0d\u591f\u5927\uff0c\u611f\u5174\u8da3\u7684\u670b\u53cb\u4e0d\u59a8\u81ea\u5df1\u9009\u62e9\u4e00\u4e2a\u8f83\u5927\u7684\u6570\u5b57\u6bd4\u8f83\u4e00\u4e0b\u4e24\u8005\u5728\u901f\u5ea6\u4e0a\u7684\u5dee\u5f02<\/p>\n<h1>total_ordering<\/h1>\n<p>Python2\u4e2d\u53ef\u4ee5\u901a\u8fc7\u81ea\u5b9a\u4e49__cmp__\u7684\u8fd4\u56de\u503c0\/-1\/1\u6765\u6bd4\u8f83\u5bf9\u8c61\u7684\u5927\u5c0f\uff0c\u5728Python3\u4e2d\u5e9f\u5f03\u4e86__cmp__\uff0c\u4f46\u662f\u6211\u4eec\u53ef\u4ee5\u901a\u8fc7totalordering\u7136\u540e\u4fee\u6539 \\_lt__() , __le__() , __gt__(), __ge__(), __eq__(), __ne__() \u7b49\u9b54\u672f\u65b9\u6cd5\u6765\u81ea\u5b9a\u4e49\u7c7b\u7684\u6bd4\u8f83\u89c4\u5219\u3002p.s: \u5982\u679c\u4f7f\u7528\u5fc5\u987b\u5728\u7c7b\u91cc\u9762\u5b9a\u4e49 __lt__() , __le__() , __gt__(), __ge__()\u4e2d\u7684\u4e00\u4e2a\uff0c\u4ee5\u53ca\u7ed9\u7c7b\u6dfb\u52a0\u4e00\u4e2a__eq__() \u65b9\u6cd5\u3002<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nimport functools\r\n@functools.total_ordering\r\nclass MyObject:\r\n    def __init__(self, val):\r\n        self.val = val\r\n    def __eq__(self, other):\r\n        print('  testing __eq__({}, {})'.format(\r\n            self.val, other.val))\r\n        return self.val == other.val\r\n    def __gt__(self, other):\r\n        print('  testing __gt__({}, {})'.format(\r\n            self.val, other.val))\r\n        return self.val &gt; other.val\r\na = MyObject(1)\r\nb = MyObject(2)\r\nfor expr in &#x5B;'a &lt; b', 'a &lt;= b', 'a == b', 'a &gt;= b', 'a &gt; b']:\r\n    print('\\n{:&lt;6}:'.format(expr))\r\n    result = eval(expr)\r\n    print('  result of {}: {}'.format(expr, result))\r\n<\/pre>\n<p>\u4e0b\u9762\u662f\u8fd0\u884c\u7ed3\u679c\uff1a<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\na &lt; b :\r\n  testing __gt__(1, 2)\r\n  testing __eq__(1, 2)\r\n  result of a &lt; b: True\r\na &lt;= b:\r\n  testing __gt__(1, 2)\r\n  result of a &lt;= b: True a == b: testing __eq__(1, 2) result of a == b: False a &gt;= b:\r\n  testing __gt__(1, 2)\r\n  testing __eq__(1, 2)\r\n  result of a &gt;= b: False\r\na &gt; b :\r\n  testing __gt__(1, 2)\r\n  result of a &gt; b: False\r\n<\/pre>\n<h1>itertools\u7684\u4f7f\u7528<\/h1>\n<p>itertools\u4e3a\u6211\u4eec\u63d0\u4f9b\u4e86\u975e\u5e38\u6709\u7528\u7684\u7528\u4e8e\u64cd\u4f5c\u8fed\u4ee3\u5bf9\u8c61\u7684\u51fd\u6570\u3002<\/p>\n<h1>\u65e0\u9650\u8fed\u4ee3\u5668<\/h1>\n<h2>count<\/h2>\n<p>count(start=0, step=1) \u4f1a\u8fd4\u56de\u4e00\u4e2a\u65e0\u9650\u7684\u6574\u6570iterator\uff0c\u6bcf\u6b21\u589e\u52a01\u3002\u53ef\u4ee5\u9009\u62e9\u63d0\u4f9b\u8d77\u59cb\u7f16\u53f7\uff0c\u9ed8\u8ba4\u4e3a0\u3002<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n&gt;&gt;&gt; from itertools import count\r\n&gt;&gt;&gt; for i in zip(count(1), &#x5B;'a', 'b', 'c']):\r\n...     print(i, end=' ')\r\n...\r\n(1, 'a') (2, 'b') (3, 'c')\r\n<\/pre>\n<h2>cycle<\/h2>\n<p>cycle(iterable) \u4f1a\u628a\u4f20\u5165\u7684\u4e00\u4e2a\u5e8f\u5217\u65e0\u9650\u91cd\u590d\u4e0b\u53bb\uff0c\u4e0d\u8fc7\u53ef\u4ee5\u63d0\u4f9b\u7b2c\u4e8c\u4e2a\u53c2\u6570\u5c31\u53ef\u4ee5\u5236\u5b9a\u91cd\u590d\u6b21\u6570\u3002<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n&gt;&gt;&gt; from itertools import cycle\r\n&gt;&gt;&gt; for i in zip(range(6), cycle(&#x5B;'a', 'b', 'c'])):\r\n...     print(i, end=' ')\r\n...\r\n(0, 'a') (1, 'b') (2, 'c') (3, 'a') (4, 'b') (5, 'c')\r\n<\/pre>\n<h2>repeat<\/h2>\n<p>repeat(object[, times]) \u8fd4\u56de\u4e00\u4e2a\u5143\u7d20\u65e0\u9650\u91cd\u590d\u4e0b\u53bb\u7684iterator\uff0c\u53ef\u4ee5\u63d0\u4f9b\u7b2c\u4e8c\u4e2a\u53c2\u6570\u5c31\u53ef\u4ee5\u9650\u5b9a\u91cd\u590d\u6b21\u6570\u3002<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n&gt;&gt;&gt; from itertools import repeat\r\n&gt;&gt;&gt; for i, s in zip(count(1), repeat('over-and-over', 5)):\r\n...     print(i, s)\r\n...\r\n1 over-and-over\r\n2 over-and-over\r\n3 over-and-over\r\n4 over-and-over\r\n5 over-and-over\r\n<\/pre>\n<p>Iterators terminating on the shortest input sequence<\/p>\n<h2>accumulate<\/h2>\n<p>accumulate(iterable[, func])<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n&gt;&gt;&gt; from itertools import accumulate\r\n&gt;&gt;&gt; import operator\r\n&gt;&gt;&gt; list(accumulate(&#x5B;1, 2, 3, 4, 5], operator.add))\r\n&#x5B;1, 3, 6, 10, 15]\r\n&gt;&gt;&gt; list(accumulate(&#x5B;1, 2, 3, 4, 5], operator.mul))\r\n&#x5B;1, 2, 6, 24, 120]\r\n<\/pre>\n<h2>chain<\/h2>\n<p>itertools.chain(*iterables)\u53ef\u4ee5\u5c06\u591a\u4e2aiterable\u7ec4\u5408\u6210\u4e00\u4e2aiterator<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n&gt;&gt;&gt; from itertools import chain\r\n&gt;&gt;&gt; list(chain(&#x5B;1, 2, 3], &#x5B;'a', 'b', 'c']))\r\n&#x5B;1, 2, 3, 'a', 'b', 'c']\r\n<\/pre>\n<p>chain\u7684\u5b9e\u73b0\u539f\u7406\u5982\u4e0b<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\ndef chain(*iterables):\r\n    # chain('ABC', 'DEF') --&gt; A B C D E F\r\n    for it in iterables:\r\n        for element in it:\r\n            yield element\r\n<\/pre>\n<h2>chain.from_iterable<\/h2>\n<p>chain.from_iterable(iterable)\u548cchain\u7c7b\u4f3c\uff0c\u4f46\u662f\u53ea\u662f\u63a5\u6536\u5355\u4e2aiterable\uff0c\u7136\u540e\u5c06\u8fd9\u4e2aiterable\u4e2d\u7684\u5143\u7d20\u7ec4\u5408\u6210\u4e00\u4e2aiterator\u3002<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n&gt;&gt;&gt; from itertools import chain\r\n&gt;&gt;&gt; list(chain.from_iterable(&#x5B;'ABC', 'DEF']))\r\n&#x5B;'A', 'B', 'C', 'D', 'E', 'F']\r\n<\/pre>\n<p>\u5b9e\u73b0\u539f\u7406\u4e5f\u548cchain\u7c7b\u4f3c<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\ndef from_iterable(iterables):\r\n    # chain.from_iterable(&#x5B;'ABC', 'DEF']) --&gt; A B C D E F\r\n    for it in iterables:\r\n        for element in it:\r\n            yield element\r\n<\/pre>\n<h2>compress<\/h2>\n<p>compress(data, selectors)\u63a5\u6536\u4e24\u4e2aiterable\u4f5c\u4e3a\u53c2\u6570\uff0c\u53ea\u8fd4\u56deselectors\u4e2d\u5bf9\u5e94\u7684\u5143\u7d20\u4e3aTrue\u7684data\uff0c\u5f53data\/selectors\u4e4b\u4e00\u7528\u5c3d\u65f6\u505c\u6b62\u3002<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n&gt;&gt;&gt; list(compress(&#x5B;1, 2, 3, 4, 5], &#x5B;True, True, False, False, True]))\r\n&#x5B;1, 2, 5]\r\n<\/pre>\n<h2>zip_longest<\/h2>\n<p>zip_longest(*iterables, fillvalue=None)\u548czip\u7c7b\u4f3c\uff0c\u4f46\u662fzip\u7684\u7f3a\u9677\u662fiterable\u4e2d\u7684\u67d0\u4e00\u4e2a\u5143\u7d20\u88ab\u904d\u5386\u5b8c\uff0c\u6574\u4e2a\u904d\u5386\u90fd\u4f1a\u505c\u6b62\uff0c\u5177\u4f53\u5dee\u5f02\u8bf7\u770b\u4e0b\u9762\u8fd9\u4e2a\u4f8b\u5b50<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nfrom itertools import zip_longest\r\nr1 = range(3)\r\nr2 = range(2)\r\nprint('zip stops early:')\r\nprint(list(zip(r1, r2)))\r\nr1 = range(3)\r\nr2 = range(2)\r\nprint('\\nzip_longest processes all of the values:')\r\nprint(list(zip_longest(r1, r2)))\r\n<\/pre>\n<p>\u4e0b\u9762\u662f\u8f93\u51fa\u7ed3\u679c<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nzip stops early:\r\n&#x5B;(0, 0), (1, 1)]\r\nzip_longest processes all of the values:\r\n&#x5B;(0, 0), (1, 1), (2, None)]\r\n<\/pre>\n<h2>islice<\/h2>\n<p>islice(iterable, stop) or islice(iterable, start, stop[, step]) \u4e0ePython\u7684\u5b57\u7b26\u4e32\u548c\u5217\u8868\u5207\u7247\u6709\u4e00\u4e9b\u7c7b\u4f3c\uff0c\u53ea\u662f\u4e0d\u80fd\u5bf9start\u3001start\u548cstep\u4f7f\u7528\u8d1f\u503c\u3002<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n&gt;&gt;&gt; from itertools import islice\r\n&gt;&gt;&gt; for i in islice(range(100), 0, 100, 10):\r\n...     print(i, end=' ')\r\n...\r\n0 10 20 30 40 50 60 70 80 90\r\n<\/pre>\n<h2>tee<\/h2>\n<p>tee(iterable, n=2) \u8fd4\u56den\u4e2a\u72ec\u7acb\u7684iterator\uff0cn\u9ed8\u8ba4\u4e3a2\u3002<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nfrom itertools import islice, tee\r\nr = islice(count(), 5)\r\ni1, i2 = tee(r)\r\nprint('i1:', list(i1))\r\nprint('i2:', list(i2))\r\nfor i in r:\r\n    print(i, end=' ')\r\n    if i &gt; 1:\r\n        break\r\n<\/pre>\n<p>\u4e0b\u9762\u662f\u8f93\u51fa\u7ed3\u679c\uff0c\u6ce8\u610ftee(r)\u540e\uff0cr\u4f5c\u4e3aiterator\u5df2\u7ecf\u5931\u6548\uff0c\u6240\u4ee5for\u5faa\u73af\u6ca1\u6709\u8f93\u51fa\u503c\u3002<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\ni1: &#x5B;0, 1, 2, 3, 4]\r\ni2: &#x5B;0, 1, 2, 3, 4]\r\n<\/pre>\n<h2>starmap<\/h2>\n<p>starmap(func, iterable)\u5047\u8bbeiterable\u5c06\u8fd4\u56de\u4e00\u4e2a\u5143\u7ec4\u6d41\uff0c\u5e76\u4f7f\u7528\u8fd9\u4e9b\u5143\u7ec4\u4f5c\u4e3a\u53c2\u6570\u8c03\u7528func\uff1a<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n&gt;&gt;&gt; from itertools import starmap\r\n&gt;&gt;&gt; import os\r\n&gt;&gt;&gt; iterator = starmap(os.path.join,\r\n...                    &#x5B;('\/bin', 'python'), ('\/usr', 'bin', 'java'),\r\n...                    ('\/usr', 'bin', 'perl'), ('\/usr', 'bin', 'ruby')])\r\n&gt;&gt;&gt; list(iterator)\r\n&#x5B;'\/bin\/python', '\/usr\/bin\/java', '\/usr\/bin\/perl', '\/usr\/bin\/ruby']\r\n<\/pre>\n<h2>filterfalse<\/h2>\n<p>filterfalse(predicate, iterable) \u4e0efilter()\u76f8\u53cd\uff0c\u8fd4\u56de\u6240\u6709predicate\u8fd4\u56deFalse\u7684\u5143\u7d20\u3002<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nitertools.filterfalse(is_even, itertools.count()) =&gt;\r\n1, 3, 5, 7, 9, 11, 13, 15, ...\r\n<\/pre>\n<h2>takewhile<\/h2>\n<p>takewhile(predicate, iterable) \u53ea\u8981predicate\u8fd4\u56deTrue\uff0c\u4e0d\u505c\u5730\u8fd4\u56deiterable\u4e2d\u7684\u5143\u7d20\u3002\u4e00\u65e6predicate\u8fd4\u56deFalse\uff0citeration\u5c06\u7ed3\u675f\u3002<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\ndef less_than_10(x):\r\n    return x &lt; 10 itertools.takewhile(less_than_10, itertools.count()) =&gt; 0, 1, 2, 3, 4, 5, 6, 7, 8, 9\r\nitertools.takewhile(is_even, itertools.count())\r\n=&gt; 0\r\n<\/pre>\n<h2>dropwhile<\/h2>\n<p>dropwhile(predicate, iterable) \u5728predicate\u8fd4\u56deTrue\u65f6\u820d\u5f03\u5143\u7d20\uff0c\u7136\u540e\u8fd4\u56de\u5176\u4f59\u8fed\u4ee3\u7ed3\u679c\u3002<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nitertools.dropwhile(less_than_10, itertools.count())\r\n=&gt; 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...\r\nitertools.dropwhile(is_even, itertools.count())\r\n=&gt; 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...\r\n<\/pre>\n<h2>groupby<\/h2>\n<p>groupby(iterable, key=None) \u628aiterator\u4e2d\u76f8\u90bb\u7684\u91cd\u590d\u5143\u7d20\u6311\u51fa\u6765\u653e\u5728\u4e00\u8d77\u3002p.s: The input sequence needs to be sorted on the key value in order for the groupings to work out as expected.<\/p>\n<ul>\n<li>[k for k, g in groupby(\u2018AAAABBBCCDAABBB\u2019)] \u2013&gt; A B C D A B<\/li>\n<li>[list(g) for k, g in groupby(\u2018AAAABBBCCD\u2019)] \u2013&gt; AAAA BBB CC D<\/li>\n<\/ul>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n&gt;&gt;&gt; import itertools\r\n&gt;&gt;&gt; for key, group in itertools.groupby('AAAABBBCCDAABBB'):\r\n...     print(key, list(group))\r\n...\r\nA &#x5B;'A', 'A', 'A', 'A']\r\nB &#x5B;'B', 'B', 'B']\r\nC &#x5B;'C', 'C']\r\nD &#x5B;'D']\r\nA &#x5B;'A', 'A']\r\nB &#x5B;'B', 'B', 'B']\r\ncity_list = &#x5B;('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL'),\r\n             ('Anchorage', 'AK'), ('Nome', 'AK'),\r\n             ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ'),\r\n             ...\r\n            ]\r\ndef get_state(city_state):\r\n    return city_state&#x5B;1]\r\nitertools.groupby(city_list, get_state) =&gt;\r\n  ('AL', iterator-1),\r\n  ('AK', iterator-2),\r\n  ('AZ', iterator-3), ...\r\niterator-1 =&gt;  ('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL')\r\niterator-2 =&gt; ('Anchorage', 'AK'), ('Nome', 'AK')\r\niterator-3 =&gt; ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ')\r\n<\/pre>\n<h1>Combinatoric generators<\/h1>\n<h2>product<\/h2>\n<p>product(*iterables, repeat=1)<\/p>\n<ul>\n<li>product(A, B) returns the same as ((x,y) for x in A for y in B)<\/li>\n<li>product(A, repeat=4) means the same as product(A, A, A, A)<\/li>\n<\/ul>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nfrom itertools import product\r\ndef show(iterable):\r\n    for i, item in enumerate(iterable, 1):\r\n        print(item, end=' ')\r\n        if (i % 3) == 0:\r\n            print()\r\n    print()\r\nprint('Repeat 2:\\n')\r\nshow(product(range(3), repeat=2))\r\nprint('Repeat 3:\\n')\r\nshow(product(range(3), repeat=3))\r\n<\/pre>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nRepeat 2:\r\n(0, 0) (0, 1) (0, 2)\r\n(1, 0) (1, 1) (1, 2)\r\n(2, 0) (2, 1) (2, 2)\r\nRepeat 3:\r\n(0, 0, 0) (0, 0, 1) (0, 0, 2)\r\n(0, 1, 0) (0, 1, 1) (0, 1, 2)\r\n(0, 2, 0) (0, 2, 1) (0, 2, 2)\r\n(1, 0, 0) (1, 0, 1) (1, 0, 2)\r\n(1, 1, 0) (1, 1, 1) (1, 1, 2)\r\n(1, 2, 0) (1, 2, 1) (1, 2, 2)\r\n(2, 0, 0) (2, 0, 1) (2, 0, 2)\r\n(2, 1, 0) (2, 1, 1) (2, 1, 2)\r\n(2, 2, 0) (2, 2, 1) (2, 2, 2)\r\n<\/pre>\n<h2>permutations<\/h2>\n<p>permutations(iterable, r=None)\u8fd4\u56de\u957f\u5ea6\u4e3ar\u7684\u6240\u6709\u53ef\u80fd\u7684\u7ec4\u5408\u3002<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nfrom itertools import permutations\r\ndef show(iterable):\r\n    first = None\r\n    for i, item in enumerate(iterable, 1):\r\n        if first != item&#x5B;0]:\r\n            if first is not None:\r\n                print()\r\n            first = item&#x5B;0]\r\n        print(''.join(item), end=' ')\r\n    print()\r\nprint('All permutations:\\n')\r\nshow(permutations('abcd'))\r\nprint('\\nPairs:\\n')\r\nshow(permutations('abcd', r=2))\r\n<\/pre>\n<p>\u4e0b\u9762\u662f\u8f93\u51fa\u7ed3\u679c<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nAll permutations:\r\nabcd abdc acbd acdb adbc adcb\r\nbacd badc bcad bcda bdac bdca\r\ncabd cadb cbad cbda cdab cdba\r\ndabc dacb dbac dbca dcab dcba\r\nPairs:\r\nab ac ad\r\nba bc bd\r\nca cb cd\r\nda db dc\r\n<\/pre>\n<h2>combinations<\/h2>\n<p>combinations(iterable, r) \u8fd4\u56de\u4e00\u4e2aiterator\uff0c\u63d0\u4f9biterable\u4e2d\u6240\u6709\u5143\u7d20\u53ef\u80fd\u7ec4\u5408\u7684r\u5143\u7ec4\u3002\u6bcf\u4e2a\u5143\u7ec4\u4e2d\u7684\u5143\u7d20\u4fdd\u6301\u4e0eiterable\u8fd4\u56de\u7684\u987a\u5e8f\u76f8\u540c\u3002\u4e0b\u9762\u7684\u5b9e\u4f8b\u4e2d\uff0c\u4e0d\u540c\u4e8e\u4e0a\u9762\u7684permutations\uff0ca\u603b\u662f\u5728bcd\u4e4b\u524d\uff0cb\u603b\u662f\u5728cd\u4e4b\u524d\uff0cc\u603b\u662f\u5728d\u4e4b\u524d\u3002<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nfrom itertools import combinations\r\ndef show(iterable):\r\n    first = None\r\n    for i, item in enumerate(iterable, 1):\r\n        if first != item&#x5B;0]:\r\n            if first is not None:\r\n                print()\r\n            first = item&#x5B;0]\r\n        print(''.join(item), end=' ')\r\n    print()\r\nprint('Unique pairs:\\n')\r\nshow(combinations('abcd', r=2))\r\n<\/pre>\n<p>\u4e0b\u9762\u662f\u8f93\u51fa\u7ed3\u679c<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nUnique pairs:\r\nab ac ad\r\nbc bd\r\ncd\r\n<\/pre>\n<h2>combinations_with_replacement<\/h2>\n<p>combinations_with_replacement(iterable, r)\u51fd\u6570\u653e\u5bbd\u4e86\u4e00\u4e2a\u4e0d\u540c\u7684\u7ea6\u675f\uff1a\u5143\u7d20\u53ef\u4ee5\u5728\u5355\u4e2a\u5143\u7ec4\u4e2d\u91cd\u590d\uff0c\u5373\u53ef\u4ee5\u51fa\u73b0aa\/bb\/cc\/dd\u7b49\u7ec4\u5408\u3002<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nfrom itertools import combinations_with_replacement\r\ndef show(iterable):\r\n    first = None\r\n    for i, item in enumerate(iterable, 1):\r\n        if first != item&#x5B;0]:\r\n            if first is not None:\r\n                print()\r\n            first = item&#x5B;0]\r\n        print(''.join(item), end=' ')\r\n    print()\r\nprint('Unique pairs:\\n')\r\nshow(combinations_with_replacement('abcd', r=2))\r\n<\/pre>\n<p>\u4e0b\u9762\u662f\u8f93\u51fa\u7ed3\u679c<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\naa ab ac ad\r\nbb bc bd\r\ncc cd\r\ndd\r\n<\/pre>\n<h1>operator\u7684\u4f7f\u7528<\/h1>\n<h2>attrgetter<\/h2>\n<p>operator.attrgetter(attr)\u548coperator.attrgetter(*attrs)<\/p>\n<ul>\n<li>After f = attrgetter(\u2018name\u2019), the call f(b) returns b.name.<\/li>\n<li>After f = attrgetter(\u2018name\u2019, \u2018date\u2019), the call f(b) returns (b.name, b.date).<\/li>\n<li>After f = attrgetter(\u2018name.first\u2019, \u2018name.last\u2019), the call f(b) returns (b.name.first, b.name.last).<\/li>\n<\/ul>\n<p>\u6211\u4eec\u901a\u8fc7\u4e0b\u9762\u8fd9\u4e2a\u4f8b\u5b50\u6765\u4e86\u89e3\u4e00\u4e0bitergetter\u7684\u7528\u6cd5\u3002<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n&gt;&gt;&gt; class Student:\r\n...     def __init__(self, name, grade, age):\r\n...         self.name = name\r\n...         self.grade = grade\r\n...         self.age = age\r\n...     def __repr__(self):\r\n...         return repr((self.name, self.grade, self.age))\r\n&gt;&gt;&gt; student_objects = &#x5B;\r\n...     Student('john', 'A', 15),\r\n...     Student('jane', 'B', 12),\r\n...     Student('dave', 'B', 10),\r\n... ]\r\n&gt;&gt;&gt; sorted(student_objects, key=lambda student: student.age)   # \u4f20\u7edf\u7684lambda\u505a\u6cd5\r\n&#x5B;('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]\r\n&gt;&gt;&gt; from operator import itemgetter, attrgetter\r\n&gt;&gt;&gt; sorted(student_objects, key=attrgetter('age'))\r\n&#x5B;('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]\r\n# \u4f46\u662f\u5982\u679c\u50cf\u4e0b\u9762\u8fd9\u6837\u63a5\u53d7\u53cc\u91cd\u6bd4\u8f83\uff0cPython\u8106\u5f31\u7684lambda\u5c31\u4e0d\u9002\u7528\u4e86\r\n&gt;&gt;&gt; sorted(student_objects, key=attrgetter('grade', 'age'))\r\n&#x5B;('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]\r\n<\/pre>\n<p>attrgetter\u7684\u5b9e\u73b0\u539f\u7406\uff1a<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\ndef attrgetter(*items):\r\n    if any(not isinstance(item, str) for item in items):\r\n        raise TypeError('attribute name must be a string')\r\n    if len(items) == 1:\r\n        attr = items&#x5B;0]\r\n        def g(obj):\r\n            return resolve_attr(obj, attr)\r\n    else:\r\n        def g(obj):\r\n            return tuple(resolve_attr(obj, attr) for attr in items)\r\n    return g\r\ndef resolve_attr(obj, attr):\r\n    for name in attr.split(&quot;.&quot;):\r\n        obj = getattr(obj, name)\r\n    return obj\r\n<\/pre>\n<h2>itemgetter<\/h2>\n<p>operator.itemgetter(item)\u548coperator.itemgetter(*items)<\/p>\n<ul>\n<li>After f = itemgetter(2), the call f(r) returns r[2].<\/li>\n<li>After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3]).<\/li>\n<\/ul>\n<p>\u6211\u4eec\u901a\u8fc7\u4e0b\u9762\u8fd9\u4e2a\u4f8b\u5b50\u6765\u4e86\u89e3\u4e00\u4e0bitergetter\u7684\u7528\u6cd5<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n&gt;&gt;&gt; student_tuples = &#x5B;\r\n...     ('john', 'A', 15),\r\n...     ('jane', 'B', 12),\r\n...     ('dave', 'B', 10),\r\n... ]\r\n&gt;&gt;&gt; sorted(student_tuples, key=lambda student: student&#x5B;2])   # \u4f20\u7edf\u7684lambda\u505a\u6cd5\r\n&#x5B;('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]\r\n&gt;&gt;&gt; from operator import attrgetter\r\n&gt;&gt;&gt; sorted(student_tuples, key=itemgetter(2))\r\n&#x5B;('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]\r\n# \u4f46\u662f\u5982\u679c\u50cf\u4e0b\u9762\u8fd9\u6837\u63a5\u53d7\u53cc\u91cd\u6bd4\u8f83\uff0cPython\u8106\u5f31\u7684lambda\u5c31\u4e0d\u9002\u7528\u4e86\r\n&gt;&gt;&gt; sorted(student_tuples, key=itemgetter(1,2))\r\n&#x5B;('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]\r\n<\/pre>\n<p>itemgetter\u7684\u5b9e\u73b0\u539f\u7406<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\ndef itemgetter(*items):\r\n    if len(items) == 1:\r\n        item = items&#x5B;0]\r\n        def g(obj):\r\n            return obj&#x5B;item]\r\n    else:\r\n        def g(obj):\r\n            return tuple(obj&#x5B;item] for item in items)\r\n    return g\r\n<\/pre>\n<h2>methodcaller<\/h2>\n<p>operator.methodcaller(name[, args\u2026])<\/p>\n<ul>\n<li>After f = methodcaller(\u2018name\u2019), the call f(b) returns b.name().<\/li>\n<li>After f = methodcaller(\u2018name\u2019, \u2018foo\u2019, bar=1), the call f(b) returns b.name(\u2018foo\u2019, bar=1)<\/li>\n<\/ul>\n<p>methodcaller\u7684\u5b9e\u73b0\u539f\u7406<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\ndef methodcaller(name, *args, **kwargs):\r\n    def caller(obj):\r\n        return getattr(obj, name)(*args, **kwargs)\r\n    return caller\r\n<\/pre>\n<p>\u539f\u6587\u94fe\u63a5\uff1ahttp:\/\/www.ziwenxie.site\/2017\/01\/15\/python-functools-itertools-operator\/<\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u5f15\u8a00 functools, itertools, operator\u662fPython\u6807\u51c6\u5e93\u4e3a\u6211\u4eec\u63d0\u4f9b\u7684\u652f\u6301\u51fd\u6570\u5f0f\u7f16 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[6],"tags":[],"class_list":["post-6167","post","type-post","status-publish","format-standard","hentry","category-code_related"],"_links":{"self":[{"href":"https:\/\/kyle.ai\/blog\/wp-json\/wp\/v2\/posts\/6167","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/kyle.ai\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/kyle.ai\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/kyle.ai\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/kyle.ai\/blog\/wp-json\/wp\/v2\/comments?post=6167"}],"version-history":[{"count":3,"href":"https:\/\/kyle.ai\/blog\/wp-json\/wp\/v2\/posts\/6167\/revisions"}],"predecessor-version":[{"id":6170,"href":"https:\/\/kyle.ai\/blog\/wp-json\/wp\/v2\/posts\/6167\/revisions\/6170"}],"wp:attachment":[{"href":"https:\/\/kyle.ai\/blog\/wp-json\/wp\/v2\/media?parent=6167"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/kyle.ai\/blog\/wp-json\/wp\/v2\/categories?post=6167"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/kyle.ai\/blog\/wp-json\/wp\/v2\/tags?post=6167"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}