Home > Net >  Checking for the existence of an instance in a list, then adding that instance to another list in py
Checking for the existence of an instance in a list, then adding that instance to another list in py

Time:04-27

I have the following list of instances:

diamondlist = []
goldlist = []
mylist = [Diamond((1, 2)), Gold((3, 4)), Diamond((2,3))]

I want to iterate through this list and check if the list contains a specific instance of an item and then add that specific instance to another list.

For example, after iterating through the list I want to have two seperate lists of:

diamondlist = [Diamond((1,2)), Diamond((2,3))]
goldlist = [Gold((3, 4))]

I don't really have an idea how to begin coding this but this is what I have so far. Note: I use 'diamondInstance' as a placeholder as I do not know what should go here.

 if diamondInstance in mylist:
   diamondlist.append(diamondInstance)

Then I would just repeat this code for Gold. Thank you in advance

CodePudding user response:

From your expected result, isinstance() is what you need.

diamondlist = []
goldlist = []
mylist = [Diamond((1, 2)), Gold((3, 4)), Diamond((2, 3))]

for item in mylist:
    if isinstance(item, Diamond):
        diamondlist.append(item)
    elif isinstance(item, Gold):
        goldlist.append(item)

CodePudding user response:

Assuming that classes "Diamond" and "Gold" (etc.) are defined like so

class Thing():

    def __init__(self,v): self.v = v
    def __repr__(self  ): return '{0}({1})'.format(type(self).__name__,self.v)

class Diamond(Thing): pass
class Gold   (Thing): pass
...

, we can iterate over an arbitrary list with any number of instances of each class and build a mapping by class name with the following routine.

import collections  # to use 'defaultdict', which comes in handy
def mapbytype(mylist):

    mappedbytype = collections.defaultdict(lambda: list())
    for element in mylist:

        mappedbytype[type(element).__name__].append(element)

    return mappedbytype

The result is a dict (collections.defaultdict) where

  • each key is the name of a class;
  • each value is the list of instances found created from such class.

Here are a few examples to try out and a function to pretty-print the results.

def printresult(dictoflists): print('\n'.join('    {0}{1}: {2}'.format(k,(10-len(k))*' ',', '.join(map(repr,l))) for k,l in dictoflists.items()))

print('Example 1')
printresult(mapbytype([Diamond((1, 2)), ]))
print('Example 2') # your original example
printresult(mapbytype([Diamond((1, 2)), Gold((3, 4)), Diamond((2,3)), ]))
print('Example 3')
printresult(mapbytype([Diamond((1, 2)), Gold((3, 4)), Diamond((2,3)), Silver((0,0)), Bronze((-1,-2)), ]))
  • Related