Pythonic pattern for creating parallel lists

I am new to Python and I find that I write the same code code over and over:

def foo(list):
    results = []
    for n in list:
        #do some or a lot of processing on N and possibly other variables
        nprime = operation(n)
        results.append(nprime)
    return results

I am thinking in particular of creating an empty list, followed by a call append. Is there a more pythonic way of expressing this pattern? appendmay not have the best performance characteristics, but I'm not sure how else I will access it in Python.

I often know the exact length of my output, so the call appendevery time seems like it might cause memory fragmentation or performance problems, but I also wonder if these are my old methods just Cup. I write a lot of parsing text code, which is not very sensitive to performance in any particular loop or fragment, because all the performance is really contained in the code gensimor NLTKand is in much more powerful hands than mine.

Is there a better / more pythonic pattern for this type of operation?

+4
source share
2 answers

-, , ( , , operation.

def foo(list):
    return [operation(n) for n in list]

, , foo .

def foo(list):
    for n in list:
        # Processing...
        yield operation(n)

, :

for x in foo(myList):
   ...

, :

results = list(foo())

, , , .

+8

[..], append , , , C, .

, . Python , ( ), O(1). list.append, ( .append) , , .

( ) ; , (LIST_APPEND , , C).

, , , chepners, .


, for - . map, . for .

+4

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


All Articles