22

How to "hide" an item in a list when you pass a list in a Python funct...

 2 years ago
source link: https://www.codesd.com/item/how-to-hide-an-item-in-a-list-when-you-pass-a-list-in-a-python-function.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to "hide" an item in a list when you pass a list in a Python function?

advertisements

Suppose I have a list

myList = [a,b,c,d,e]

And a function

def doSomething(list):
    #Does something to the list

And I want to call the function iteratively like this:

doSomething([b,c,d,e])
doSomething([a,c,d,e])
doSomething([a,b,d,e])
doSomething([a,b,c,e])
doSomething([a,b,c,d])

The first thing that comes to mind would be something like this:

for x in range(0,len(myList)):
    del myList[x]
    doSomething(myList)

But this doesn't really work, because each time I call del it actually deletes the element. I sort of just want to 'hide' the element each time I call the function. Is there a way to do this?


You can use itertools.combinations for this:

import itertools

for sublist in itertools.combinations([a, b, c, d, e], 4):
    # 4 is the number of elements in each sublist.
    # If you do not know the length of the input list, use len() - 1
    doSomething(sublist)

This will make sublist a tuple. If you need it to be a list, you can call list() on it before passing it to doSomething().

If you care about the order in which the doSomething() calls are done, you will want to reverse the order of iteration so that it begins by removing the first element instead of the last element:

for sublist in reversed(list(itertools.combinations([a, b, c, d, e], 4))):
    doSomething(sublist)

This is less efficient because all of the sublists must be generated up front instead of one at a time. mgilson in the comments suggests reversing the input list and then reversing each sublist, which should be more efficient but the code may be harder to read.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK