6.7 利用 any 代替 for 循环 ========================== .. image:: http://image.iswbm.com/20200804124133.png 在æŸäº›åœºæ™¯ä¸‹ï¼Œæˆ‘们需è¦åˆ¤æ–是å¦æ»¡è¶³æŸä¸€ç»„集åˆä¸ä»»æ„一个æ¡ä»¶ 这时候,很多åŒå¦è‡ªç„¶ä¼šæƒ³åˆ°ä½¿ç”¨ for 循环。 .. code:: python found = False for thing in things: if thing == other_thing: found = True break 但其实更好的写法,是使用 ``any()`` 函数,能够使这段代ç å˜å¾—æ›´åŠ æ¸…æ™°ã€ç®€æ´ .. code:: python found = any(thing == other_thing for thing in things) 使用 any 并ä¸ä¼šå‡å°‘ for 循环的次数,åªè¦æœ‰ä¸€ä¸ªæ¡ä»¶ä¸º True,any 就能得到结果。 åŒç†ï¼Œå½“ä½ éœ€è¦åˆ¤æ–是å¦æ»¡è¶³æŸä¸€ç»„集åˆä¸æ‰€æœ‰æ¡ä»¶ï¼Œä¹Ÿå¯ä»¥ä½¿ç”¨ ``all()`` 函数。 .. code:: python found = all(thing == other_thing for thing in things) åªè¦æœ‰ä¸€ä¸ªä¸æ»¡è¶³æ¡ä»¶ï¼Œall 函数的结果就会立刻返回 False