Mapping maps and lists in Python

Possible duplicate:
Python List Consrehension Vs. Map

When should you use map / filter instead of an expression to list or a generator expression?

+3
source share
2 answers

You can see the answers to this question:

Python List Consrehension Vs. Map

In addition, there is a corresponding essay from Guido, creator and BDFL Python:

http://www.artima.com/weblogs/viewpost.jsp?thread=98196

Personally, I prefer the use of generator lists and expressions, because their meaning is more obvious when reading code.

+5
source

pythonic. python , , , -.

, . . , . , . , . .

, , , .

k=1000

def transform(input):
    return input + 1

"""
  1. range(k) allocates a k element list [0...k]
  2. Iterate over each element in that list and compute the transform
  3. Store the results in a list
  4. Pass the list to sum

Memory: Allocates enough 2 lists of size k
"""
print sum([transform(i) for i in range(k)])

"""
  1. Create an xrange object
  2. Pass transform and xrange object to map
  3. Map returns a list of results [1...k+1]
  4. Pass list to sum

Memory: Creates a constant size object and creates a list of size k
"""
print sum(map(transform, xrange(k)))

"""
  1. Create an xrange object
  2. Create a generator object
  3. Pass generator object to sum

Memory: Allocates 2 objects of constant size
"""
print sum(transform(i) for i in xrange(k))

"""
Create a generator object and operate on it directly
"""
g = (transform(i) for i in xrange(k))
print dir(g)
print g.next()
print g.next()
print g.next()
+1

Source: https://habr.com/ru/post/1748634/


All Articles