Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to directly extend multiple lists using a tuple of lists returned by a function?

Tags:

python

I have a function that checks for file and directory changes within a given function and returns a tuple of lists, like this: addedFiles, removedFiles, addedDirs, removedDirs. Each of the named sublists in the tuple will be a list of strings (or empty). I need to append the results return by the function to local versions of these lists.

This heavily modified demonstrates the result I am after:

addedFiles, removedFiles, addedDirs, removedDirs = [],[],[],[]

for dir in allDirs:
    a,b,c,d = scanDir( dir )
    addedFiles.extend( a )
    removedFiles.extend( b )
    addedDirs.extend( c )
    removedDirs.extend( d )

But, I want to know if there is a better way to perform the section inside the for loop?
Like this it just feels a bit ... ugly.

like image 396
DMA57361 Avatar asked Nov 24 '25 12:11

DMA57361


2 Answers

How about:

 for a,b in zip(lists, extendwith):
     a.extend(b)
like image 148
Andreas Avatar answered Nov 26 '25 18:11

Andreas


params = ('addedFiles', 'removedFiles', 'addedDirs', 'removedDirs')
paramDict = dict((param, []) for param in params)

for dir in allDirs:
    for param, data in zip(params, scanDir(dir)):
        paramDict[param].extend(data)

Now you have a dict of lists instead of four lists.

like image 31
eumiro Avatar answered Nov 26 '25 18:11

eumiro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!