PythonµÄlambdaº¯ÊýÓëÅÅÐò
Ç°¼¸Ìì¿´µ½ÁËÒ»ÐÐÇó1000µÄ½×³ËµÄPython´úÂ룺
print
reduce
(
lambda
x
,
y
:
x
*
y
,
range
(
1
,
1001
))
Ò»ÏÂ×Ó±»python´úÂëµÄ¾«¼ò
Óë½ô´ÕËùÕÛ·þ£¬¹Ê¶Ô´úÂë½øÐÐÁ˼òµ¥µÄ·ÖÎö¡£
reduceÓërange¶¼ÊÇPythonµÄÄÚÖú¯Êý¡£
range£¨1£¬1001£©
±íʾÉú³É1µ½1000µÄÁ¬ÐøÕûÊýÁÐ±í£¨List£©¡£
reduce£¨functionA£¬iterableB£©£¬functionAΪÐèÒªÁ½
¸ö±äÁ¿µÄº¯Êý£¬²¢·µ»ØÒ»¸öÖµ¡£iterableBΪ¿Éµü´ú±äÁ¿£¬ÈçListµÈ¡£reduceº¯Êý½«BÖеÄÔªËØ´Ó×óµ½ÓÒÒÀ´Î´«È뺯ÊýAÖУ¬ÔÙÓú¯ÊýA·µ»ØµÄ
½á¹ûÌæ´ú´«ÈëµÄ²ÎÊý£¬·´¸´Ö´ÐУ¬Ôò¿É½«B
reduce³ÉÒ»¸öµ¥Öµ¡£ÔÚ´Ë£¬Êǽ«1µ½1000µÄÁ¬ÐøÕûÊýÁÐ±í´«Èëlambdaº¯Êý²¢ÓÃÁ½¸öÊýµÄ»ýÌæ»»ÁбíÖеÄÊý£¬Êµ¼ÊµÄ¼ÆËã¹ý³ÌΪ£º(...
((1×2)×3)×4)×...×1000)£¬×îºóµÄ½á¹û¼´1000µÄ½×³Ë¡£
ÏÂÃæÀ´½éÉÜÒ»ÏÂlambdaº¯Êý¡£
lambda
º¯ÊýÊÇÒ»ÖÖ¿ìËÙ¶¨Òåµ¥ÐеÄ×îСº¯Êý£¬ÊÇ´Ó Lisp
½èÓÃÀ´µÄ£¬¿ÉÒÔÓÃÔÚÈκÎÐèÒªº¯ÊýµÄµØ·½¡£ÏÂÃæµÄÀý×ӱȽÏÁË´«Í³µÄº¯ÊýÓëlambdaº¯ÊýµÄ¶¨Ò巽ʽ£º
1
>>>
def
f
(
x
,y):
2
...
return
x
*
y
3
...
4
>>>
f
(
2,3
)
5
6
6
>>>
g
=
lambda
x
,y:
x
*
y
7
>>>
g
(
2,3
)
8
6
¿ÉÒÔ¿´µ½£¬Á½¸öº¯Êý
µÃµ½µÄ½á¹ûÒ»Ñù£¬¶ø¶ÔÓÚʵÏÖ¼òµ¥¹¦Äܵĺ¯ÊýÀ´Ëµ£¬Ê¹ÓÃlambdaº¯ÊýÀ´¶¨Òå¸ü¼Ó¾«¼òÁé»î£¬»¹¿ÉÒÔÖ±½Ó°Ñº¯Êý¸³Öµ¸øÒ»¸ö±äÁ¿£¬ÓñäÁ¿ÃûÀ´±íʾº¯ÊýÃû¡£
Æäʵlambdaº¯ÊýÔںܶàʱºò¶¼ÊDz»ÐèÒª¸³Öµ¸øÒ»¸ö±äÁ¿µÄ£¨ÈçÇ°ÎÄÖÐÇó½×³ËµÄ¹ý³Ì£©¡£
ʹÓÃlambdaº¯Êý»¹ÓÐһЩעÒâÊÂÏ
lambda º¯Êý¿ÉÒÔ½ÓÊÕÈÎÒâ¶à¸ö²ÎÊý (°üÀ¨¿ÉÑ¡²ÎÊý) ²¢ÇÒ·µ»Øµ¥¸ö±í´ïʽµÄÖµ¡£
lambda º¯Êý²»ÄÜ°üº¬ÃüÁ°üº¬µÄ±í´ïʽ²»Äܳ¬¹ýÒ»¸ö¡£
ÏÂÃæ¼òµ¥ÑÝʾһÏÂÈçºÎʹÓÃlambdaº¯ÊýʵÏÖ×Ô¶¨ÒåÅÅÐò¡£
01
class
People
:
02
age
=
0
03
gender
=
'male'
04
05
def
__init__
(
self
,
age
,
gender
):
06
self
.
age
=
age
07
&
Ïà¹ØÎĵµ£º
¼ò½é
ÄãÒѾѧϰÁËÈçºÎÔÚÄãµÄ³ÌÐòÖж¨ÒåÒ»´Îº¯Êý¶øÖØÓôúÂë¡£Èç¹ûÄãÏëÒªÔÚÆäËû³ÌÐòÖÐÖØÓúܶຯÊý£¬ÄÇôÄã¸ÃÈçºÎ±àд³ÌÐòÄØ£¿Äã¿ÉÄÜÒѾ²Âµ½ÁË£¬´ð°¸ÊÇʹÓÃÄ£¿é¡£Ä£¿é»ù±¾ÉϾÍÊÇÒ»¸ö°üº¬ÁËËùÓÐÄ㶨ÒåµÄº¯ÊýºÍ±äÁ¿µÄÎļþ¡£ÎªÁËÔÚÆäËû³ÌÐòÖÐÖØÓÃÄ£¿é£¬Ä£¿éµÄÎļþÃû±ØÐëÒÔ.pyΪÀ©Õ¹Ãû¡£
Ä£¿é¿ÉÒÔ´ÓÆäËû³ÌÐò ÊäÈë ÒÔ±ãÀûÓÃËüµ ......
Ò»¡¢ÈçºÎÄÜÔÚÃüÁîÐÐģʽÏÂÔËÐÐPythonÃüÁ
ΪÁËÔÚÃüÁîÐÐģʽÏÂÔËÐÐPythonÃüÁÐèÒª½«python.exeËùÔÚµÄĿ¼¸½¼Óµ½PATHÕâ¸ö»·¾³±äÁ¿ÖС£
¶þ¡¢ÈçºÎʹPython½âÊÍÆ÷ÄÜÖ±½ÓimportĬÈÏ°²×°Â·¾¶ÒÔÍâµÄµÚÈý·½Ä£¿é£¿
ΪÁËÄÜimportĬÈÏ°²×°Â·¾¶ÒÔÍâµÄµÚÈý·½µÄÄ£¿é£¨Èç×Ô¼ºÐ´µÄÄ£¿é£©£¬ÐèҪн¨PYTHONPATH»·¾³±äÁ¿£¬»·¾³±äÁ¿µÄÖµÉè ......
Python ÐòÁÐ
ÁÐ±í¡¢Ôª×éºÍ×Ö·û´®¶¼ÊÇÐòÁУ¬µ«ÊÇÐòÁÐÊÇʲô£¬ËüÃÇΪʲôÈç´ËÌرðÄØ£¿ÐòÁеÄÁ½¸öÖ÷ÒªÌصãÊÇË÷Òý²Ù×÷·ûºÍÇÐƬ²Ù×÷·û¡£Ë÷Òý²Ù×÷·ûÈÃÎÒÃÇ¿ÉÒÔ´ÓÐòÁÐÖÐץȡһ¸öÌض¨ÏîÄ¿¡£ÇÐƬ²Ù×÷·ûÈÃÎÒÃÇÄܹ»»ñÈ¡ÐòÁеÄÒ»¸öÇÐƬ£¬¼´Ò»²¿·ÖÐòÁС£
ʹÓÃÐòÁÐ
Àý9.5 ʹÓÃÐòÁÐ
#!/usr/bin/python
# Filename: seq.py
shoplist ......
Áбí
listÊÇ´¦ÀíÒ»×éÓÐÐòÏîÄ¿µÄÊý¾Ý½á¹¹£¬¼´Äã¿ÉÒÔÔÚÒ»¸öÁбíÖд洢һ¸ö ÐòÁÐ
µÄÏîÄ¿¡£¼ÙÏëÄãÓÐÒ»¸ö¹ºÎïÁÐ±í£¬ÉÏÃæ¼ÇÔØ×ÅÄãÒªÂòµÄ¶«Î÷£¬Äã¾ÍÈÝÒ×Àí½âÁбíÁË¡£Ö»²»¹ýÔÚÄãµÄ¹ºÎï±íÉÏ£¬¿ÉÄÜÿÑù¶«Î÷¶¼¶À×ÔÕ¼ÓÐÒ»ÐУ¬¶øÔÚPythonÖУ¬
ÄãÔÚÿ¸öÏîÄ¿Ö®¼äÓöººÅ·Ö¸î¡£
ÁбíÖеÄÏîÄ¿Ó¦¸Ã°üÀ¨ÔÚ·½À¨ºÅÖУ¬ÕâÑùPython¾ÍÖªµÀÄãÊÇ ......
¶Ô Python º¯ÊýµÄ"µ÷ÖÆ"£¬ÊÇÖ¸¶ÔÆä×ö³öºÏºõÐèÇóµÄÉèÖ᣾ßÌåµÄµ÷ÖÆ·½·¨£¬Êǽ«Æä²ÎÊýÉèΪ¹Ì¶¨Öµ£¨³£Êý£©¡£
É趨µ¥Ò»µÄ²ÎÊýÖµ
ÔÏȵĺ¯ÊýÊÇÕâÑùµÄ£º
>>> def foo(cooked, standard):
... print "foo called with cooked: %s, standard: %s" % \
... (cooked, standard)
µ÷ÓÃËü£º
>>> foo('a', ......