﻿lambda argument1, argument2,... argumentN : wyrażenie wykorzystujące argumenty


>>> def func(x, y, z): return x + y + z
...
>>> func(2, 3, 4)
9


>>> f = lambda x, y, z: x + y + z
>>> f(2, 3, 4)
9


>>> x = (lambda a="raz", b="dwa", c="trzy": a + b + c)
>>> x("las")
'lasdwatrzy'


>>> def knights( ):
...    title = 'Sir'
...    action = (lambda x: title + ' ' + x)  # Tytuł w instrukcji def zawierającej lambda
...    return action                         # Zwrócenie funkcji
...
>>> act = knights( )
>>> act('Robin')
'Sir Robin'


L = [(lambda x: x**2), (lambda x: x**3), (lambda x: x**4)]

for f in L:
   print f(2)                                # Wyświetla 4, 8, 16

print L[0](3)                                # Wyświetla 9


>>> key = 'już'
>>> {'mam': (lambda: 2 + 2),
...  'już': (lambda: 2 * 4),
...  'jeden': (lambda: 2 ** 6)
... }[key]( )
8


def f1( ): return 2 + 2
def f2( ): return 2 * 4
def f3( ): return 2 ** 6
...

key = 'jeden'
{'mam': f1, 'już': f2, 'jeden': f3}[key]( )


if a:
   b
else:
   c


b if a else c

((a and b) or c)


>>> lower = (lambda x, y: x if x < y else y)
>>> lower('bb', 'aa')
'aa'
>>> lower('aa', 'bb')
'aa'


>>> import sys
>>> showall = (lambda x: map(sys.stdout.write, x))

>>> t = showall(['mielonka\n', 'tost\n', 'jajka\n'])
mielonka
tost
jajka

>>> showall = lambda x: [sys.stdout.write(line) for line in x]

>>> t = showall(('patrz\n', 'na\n', 'życie\n', 'z\n', 'humorem\n'))
patrz
na
życie
z
humorem


>>> def action(x):
...    return (lambda y: x + y)              # Utworzenie i zwrócenie funkcji, pamiętanie x
...
>>> act = action(99)
>>> act
<function <lambda> at 0x00A16A88>
>>> act(2)
101


>>> action = (lambda x: (lambda y: x + y))
>>> act = action(99)
>>> act(3)
102
>>> ((lambda x: (lambda y: x + y))(99))(4)
103


import sys
x = Button(
    text ='Naciśnij mnie',
    command=(lambda:sys.stdout.write('Mielonka\n')))


class MyGui:
   def makewidgets(self):
      Button(command=(lambda: self.display("mielonka")))
   def display(self, message):
      ...użycie komunikatu...


>>> def func(x, y, z): return x + y + z
...
>>> apply(func, (2, 3, 4))
9
>>> f = lambda x, y, z: x + y + z
>>> apply(f, (2, 3, 4))
9


if <test>:
   action, args = func1, (1,)
else:
   action, args = func2, (1, 2, 3)
...
apply(action, args)


>>> args = (2,3) + (4,)
>>> args
(2, 3, 4)
>>> apply(func, args)
9


>>> def echo(*args, **kwargs): print args, kwargs
...
>>> echo(1, 2, a=3, b=4)
(1, 2) {'a': 3, 'b': 4}


>>> pargs = (1, 2)
>>> kargs = {'a':3, 'b':4}
>>> apply(echo, pargs, kargs)
(1, 2) {'a': 3, 'b': 4}


>>> apply(func, args)                        # Tradycyjnie: krotka
9
>>> func(*args)                              # Nowa składnia podobna do apply
9
>>> echo(*pargs, **kargs)                    # Także słowniki ze słowami kluczowymi
(1, 2) {'a': 3, 'b': 4}


>>> echo(0, *pargs, **kargs)                 # Normalny argument, *krotka, **słownik
(0, 1, 2) {'a': 3, 'b': 4}


>>> counters = [1, 2, 3, 4]
>>>
>>> updated = []
>>> for x in counters:
...    updated.append(x + 10)                # Dodanie 10 do każdego elementu
...
>>> updated
[11, 12, 13, 14]


>>> def inc(x): return x + 10                # Funkcja do wykonania
...
>>> map(inc, counters)                       # Zebranie wyników
[11, 12, 13, 14]


>>> map((lambda x: x + 3), counters)         # Wyrażenie funkcji
[4, 5, 6, 7]


>>> def mymap(func, seq):
...    res = []
...    for x in seq: res.append(func(x))
...    return res
...
>>> map(inc, [1, 2, 3])
[11, 12, 13]
>>> mymap(inc, [1, 2, 3])
[11, 12, 13]


>>> pow(3, 4)
81
>>> map(pow, [1, 2, 3], [2, 3, 4])           # 1**2, 2**3, 3**4
[1, 8, 81]


>>> range(-5, 5)
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]

>>> filter((lambda x: x > 0), range(-5, 5))
[1, 2, 3, 4]


>>> res = [ ]
>>> for x in range(-5, 5):
...    if x > 0:
...       res.append(x)
...
>>> res
[1, 2, 3, 4]


>>> reduce((lambda x, y: x + y), [1, 2, 3, 4])
10
>>> reduce((lambda x, y: x * y), [1, 2, 3, 4])
24


>>> L = [1,2,3,4]
>>> res = L[0]
>>> for x in L[1:]:
...    res = res + x
...
>>> res
10


>>> def myreduce(function, sequence):
...    tally = sequence[0]
...    for next in sequence[1:]:
...       tally = function(tally, next)
...    return tally
...
>>> myreduce((lambda x, y: x + y), [1, 2, 3, 4, 5])
15
>>> myreduce((lambda x, y: x * y), [1, 2, 3, 4, 5])
120


>>> import operator
>>> reduce(operator.add, [2, 4, 6])          # Dodawanie oparte na funkcji
12
>>> reduce((lambda x, y: x + y), [2, 4, 6])
12


>>> ord('s')
115


>>> res = []
>>> for x in 'mielonka':
...    res.append(ord(x))
...
>>> res
[109, 105, 101, 108, 111, 110, 107, 97]


>>> res = map(ord, 'mielonka')               # Zastosowanie funkcji do sekwencji
>>> res
[109, 105, 101, 108, 111, 110, 107, 97]


>>> res = [ord(x) for x in 'mielonka']       # Zastosowanie wyrażenia do sekwencji
>>> res
[109, 105, 101, 108, 111, 110, 107, 97]


>>> [x ** 2 for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]


>>> map((lambda x: x ** 2), range(10))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]


>>> [x for x in range(5) if x % 2 == 0]
[0, 2, 4]

>>> filter((lambda x: x % 2 == 0), range(5))
[0, 2, 4]

>>> res = [ ]
>>> for x in range(5):
...    if x % 2 == 0:
...       res.append(x)
...
>>> res
[0, 2, 4]


>>> [x ** 2 for x in range(10) if x % 2 == 0]
[0, 4, 16, 36, 64]


>>> map((lambda x: x**2), filter((lambda x: x % 2 == 0), range(10)))
[0, 4, 16, 36, 64]


[ wyrażenie for cel1 in sekwencja1 [if warunek]
            for cel2 in sekwencja2 [if warunek] ...
            for celN in sekwencjaN [if warunek] ]


>>> res = [x + y for x in [0, 1, 2] for y in [100, 200, 300]]
>>> res
[100, 200, 300, 101, 201, 301, 102, 202, 302]


>>> res = []
>>> for x in [0, 1, 2]:
...    for y in [100, 200, 300]:
...       res.append(x + y)
...
>>> res
[100, 200, 300, 101, 201, 301, 102, 202, 302]


>>> [x + y for x in 'jajko' for y in 'JAJKO']
['jJ', 'jA', 'jJ', 'jK', 'jO', 'aJ', 'aA', 'aJ', 'aK', 'aO', 'jJ', 'jA', 'jJ', 'jK', 'jO', 'kJ', 'kA', 'kJ', 'kK', 'kO', 'oJ', 'oA', 'oJ', 'oK', 'oO']


>>> [(x, y) for x in range(5) if x % 2 == 0 for y in range(5) if y % 2 == 1]
[(0, 1), (0, 3), (2, 1), (2, 3), (4, 1), (4, 3)]


>>> res = []
>>> for x in range(5):
...    if x % 2 == 0:
...       for y in range(5):
...          if y % 2 == 1:
...             res.append((x, y))
...
>>> res
[(0, 1), (0, 3), (2, 1), (2, 3), (4, 1), (4, 3)]


>>> M = [[1, 2, 3],
...      [4, 5, 6],
...      [7, 8, 9]]
>>> N = [[2, 2, 2],
...      [3, 3, 3],
...      [4, 4, 4]]


>>> M[1]
[4, 5, 6]

>>> M[1][2]
6


>>> [row[1] for row in M]
[2, 5, 8]

>>> [M[row][1] for row in (0, 1, 2)]
[2, 5, 8]


>>> [M[i][i] for i in range(len(M))]
[1, 5, 9]


>>> [M[row][col] * N[row][col] for row in range(3) for col in range(3)]
[2, 4, 6, 12, 15, 18, 28, 32, 36]

>>> [[M[row][col] * N[row][col] for col in range(3)] for row in range(3)]
[[2, 4, 6], [12, 15, 18], [28, 32, 36]]


>>> res = []
>>> for row in range(3):
...    tmp = []
...    for col in range(3):
...       tmp.append(M[row][col] * N[row][col])
...    res.append(tmp)
...
>>> res
[[2, 4, 6], [12, 15, 18], [28, 32, 36]]


>>> open('myfile').readlines( )
['aaa\n', 'bbb\n', 'ccc\n']


>>> [line.rstrip( ) for line in open('myfile').readlines( )]
['aaa', 'bbb', 'ccc']

>>> [line.rstrip( ) for line in open('myfile')]
['aaa', 'bbb', 'ccc']

>>> map((lambda line: line.rstrip( )), open('myfile'))
['aaa', 'bbb', 'ccc']


listoftuple = [('Teodor', 35, 'dyrektor'), ('Teofil', 40, 'prezes')]


>>> [age for (name, age, job) in listoftuple]
[35, 40]

>>> map((lambda (name, age, job): age), listoftuple)
[35, 40]


>>> def gensquares(N):
...    for i in range(N):
...       yield i ** 2                       # Wznowienie odtąd
...


>>> for i in gensquares(5):                  # Wznowienie funkcji
...    print i, ':',                         # Wyświetlenie ostatniej uzyskanej wartości
...
0 : 1 : 4 : 9 : 16 :
>>>


>>> x = gensquares(4)
>>> x
<generator object at 0x0086C378>


>>> x.next( )
0
>>> x.next( )
1
>>> x.next( )
4
>>> x.next( )
9
>>> x.next( )
Traceback (most recent call last):
   File "<pyshell#453>", line 1, in <module>
      x.next( )
StopIteration


>>> def buildsquares(n):
...    res = []
...    for i in range(n): res.append(i**2)
...    return res
...
>>> for x in buildsquares(5): print x, ':',
...
0 : 1 : 4 : 9 : 16 :


>>> for x in [n**2 for n in range(5)]:
...    print x, ':',
...
0 : 1 : 4 : 9 : 16 :

>>> for x in map((lambda x:x**2), range(5)):
...    print x, ':',
...
0 : 1 : 4 : 9 : 16 :


>>> D = {'a':1, 'b':2, 'c':3}
>>> x = iter(D)
>>> x.next( )
'a'
>>> x.next( )
'c'


>>> for key in D:
...    print key, D[key]
...
a 1
c 3
b 2


>>> for line in open('temp.txt'):
...    print line,
...
To rana
powierzchowna.


>>> [x ** 2 for x in range(4)]               # Lista składana - zbudowanie listy
[0, 1, 4, 9]

>>> (x ** 2 for x in range(4))               # Wyrażenie generatora - utworzenie obiektu, po którym można iterować
<generator object at 0x011DC648>


>>> G = (x ** 2 for x in range(4))
>>> G.next( )
0
>>> G.next( )
1
>>> G.next( )
4
>>> G.next( )
9
>>> G.next( )
Traceback (most recent call last):
   File "<pyshell#410>", line 1, in <module>
      G.next( )
StopIteration


>>> for num in (x ** 2 for x in range(4)):
...    print '%s, %s' % (num, num / 2.0)
...
0, 0.0
1, 0.5
4, 2.0
9, 4.5


>>> sum(x ** 2 for x in range(4))
14

>>> sorted(x ** 2 for x in range(4))
[0, 1, 4, 9]

>>> sorted((x ** 2 for x in range(4)), reverse=True)
[9, 4, 1, 0]

>>> import math
>>> map(math.sqrt, (x ** 2 for x in range(4)))
[0.0, 1.0, 2.0, 3.0]


# Plik timerseqs.py

import time, sys
reps = 1000
size = 10000

def tester(func, *args):
   startTime = time.time( )
   for i in range(reps):
      func(*args)
   elapsed = time.time( ) - startTime
   return elapsed

def forStatement( ):
   res = []
   for x in range(size):
      res.append(abs(x))

def listComprehension( ):
   res = [abs(x) for x in range(size)]

def mapFunction( ):
   res = map(abs, range(size))

def generatorExpression( ):
   res = list(abs(x) for x in range(size))

print sys.version
tests = (forStatement, listComprehension, mapFunction, generatorExpression)
for testfunc in tests:
   print testfunc.__name__.ljust(20), '=>', tester(testfunc)


2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)]
forStatement        => 6.10899996758
listComprehension   => 3.51499986649
mapFunction         => 2.73399996758
generatorExpression => 4.11600017548


...
...
def forStatement( ):
   res = []
   for x in range(size):
      res.append(x + 10)

def listComprehension( ):
   res = [x + 10 for x in range(size)]

def mapFunction( ):
   res = map((lambda x: x + 10), range(size))

def generatorExpression( ):
   res = list(x + 10 for x in range(size))
...
...


2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)]
forStatement        => 5.25699996948
listComprehension   => 2.68400001526
mapFunction         => 5.96900010109
generatorExpression => 3.37400007248


>>> def echo(message):                       # Zmienna echo przypisana do obiektu funkcji
...    print message
...
>>> x = echo                                 # Teraz x jest także referencją do niego
>>> x('Witaj, świecie!')                     # Wywołanie obiektu przez dodanie ( )
Witaj, świecie!


>>> def indirect(func, arg):
...    func(arg)                             # Wywołanie obiektu przez dodanie ( )
...
>>> indirect(echo, 'Witaj, trollu!')         # Przekazanie funkcji do funkcji
Witaj, trollu!


>>> schedule = [ (echo, 'Mielonka!'), (echo, 'Szynka!') ]
>>> for (func, arg) in schedule:
...    func(arg)
...
Mielonka!
Szynka!


>>> X = 99
>>> def selector( ):                         # X wykorzystana, ale nie przypisana
...    print X                               # X znaleziona w zakresie globalnym
...
>>> selector( )
99


>>> def selector( ):
...    print X                               # Jeszcze nie istnieje!
...    X = 88                                # X sklasyfikowana jako zmienna lokalna (wszędzie)
...                                          # To samo przy "import X", "def X"...
>>> selector( )
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "<stdin>", line 2, in selector
UnboundLocalError: local variable 'X' referenced before assignment


>>> def selector( ):
...    global X                              # Zmienna X będzie globalna (wszędzie)
...    print X
...    X = 88
...
>>> selector( )
99


>>> X = 99
>>> def selector( ):
...    import __main__                       # Importowanie modułu zawierającego
...    print __main__.X                      # Notacja z atrybutem pozwala otrzymać zmienną globalną
...    X = 88                                # Zmienna X niebędąca atrybutem staje się lokalna
...    print X                               # Wyświetla lokalną wersję zmiennej
...
>>> selector( )
99
88


>>> def saver(x=[]):                         # Zapisuje listę obiektów
...    x.append(1)                           # Za każdym razem modyfikuje ten sam obiekt!
...    print x
...
>>> saver([2])                               # Wartość domyślna nie zostaje użyta
[2, 1]
>>> saver( )                                 # Wartość domyślna zostaje użyta
[1]
>>> saver( )                                 # Rośnie z każdym wywołaniem!
[1, 1]
>>> saver( )
[1, 1, 1]


>>> def saver(x=None):
...    if x is None:                         # Nie przekazano argumentu?
...       x = []                             # Wykonanie kodu tworzącego nową listę
...    x.append(1)                           # Zmiana nowego obiektu listy
...    print x
...
>>> saver([2])
[2, 1]
>>> saver( )                                 # Tutaj lista nie rośnie
[1]
>>> saver( )
[1]


>>> def proc(x):
...    print x                               # Brak instrukcji return to zwrócenie None
...
>>> x = proc('testowanie 123...')
testowanie 123...
>>> print x
None


>>> list = [1, 2, 3]
>>> list = list.append(4)                    # append jest "procedurą"
>>> print list                               # append modyfikuje listę w miejscu
None


def f1(a, b): print a, b                     # Normalne argumenty

def f2(a, *b): print a, b                    # Zmienna liczba argumentów pozycyjnych

def f3(a, **b): print a, b                   # Zmienna liczba słów kluczowych

def f4(a, *b, **c): print a, b, c            # Tryby mieszane

def f5(a, b=2, c=3): print a, b, c           # Wartości domyślne

def f6(a, b=2, *c): print a, b, c            # Zmienna liczba argumentów pozycyjnych i wartości domyślnych


>>> f1(1, 2)
>>> f1(b=2, a=1)

>>> f2(1, 2, 3)
>>> f3(1, x=2, y=3)
>>> f4(1, 2, 3, x=2, y=3)

>>> f5(1)
>>> f5(1, 4)

>>> f6(1)
>>> f6(1, 3, 4)


x = y / 2                                    # Dla jakiegoś y > 1
while x > 1:
   if y % x == 0:                            # Reszta
      print y, 'ma czynnik', x
      break                                  # Pominięcie reszty
   x = x-1
else:                                        # Normalne wyjście
   print y, 'jest liczbą pierwszą'


13 jest liczbą pierwszą
13.0 jest liczbą pierwszą
15 ma czynnik 5
15.0 ma czynnik 5.0