SlideShare une entreprise Scribd logo
1  sur  48
Télécharger pour lire hors ligne
Lightning Talk
collections
André Ericson
Dezembro/2011, Pug-Pe
collections
Roteiro




    • Counter
    • deque
    • namedtuple
    • OrderedDict
    • abc
    • collections.abc
collections.Counter
Counter


          >>> c = Counter([’a’, ’b’, ’c’, ’d’, ’a’, ’d’, ’b’])
          >>> print c
          Counter({’a’: 2, ’b’: 2, ’d’: 2, ’c’: 1})

          # Funciona como um dicionario
          >>> print c[’a’]
          2
          >>> c[’a’] += 1
          >>> print c
          Counter({’a’: 3, ’b’: 2, ’d’: 2, ’c’: 1})

          >>> print c[’e’] # Retorna 0 ao inves de levantar KeyError
          0

          >>> c.most_common(3)
          [(’a’, 3), (’b’, 2), (’d’, 2)]
          >>> c[’f’] = ’asdad’ # Pode adicionar qualquer coisa
          >>> print c
          Counter({’f’: ’asdad’, ’a’: 3, ’b’: 2, ’d’: 2, ’c’: 1})
          >>> c[’f’] > c[’a’]
          True

          >>> c.update([’a’, ’b’, ’b’, ’d’])
          # c.subtract(iterable-or-mapping) faz o subtracao de elementos
          >>> print c
          Counter({’f’: ’asdad’, ’a’: 4, ’b’: 4, ’d’: 3, ’c’: 1})
Counter


          >>> c = Counter([’a’, ’b’, ’c’, ’d’, ’a’, ’d’, ’b’])
          >>> print c
          Counter({’a’: 2, ’b’: 2, ’d’: 2, ’c’: 1})

          # Funciona como um dicionario
          >>> print c[’a’]
          2
          >>> c[’a’] += 1
          >>> print c
          Counter({’a’: 3, ’b’: 2, ’d’: 2, ’c’: 1})

          >>> print c[’e’] # Retorna 0 ao inves de levantar KeyError
          0

          >>> c.most_common(3)
          [(’a’, 3), (’b’, 2), (’d’, 2)]
          >>> c[’f’] = ’asdad’ # Pode adicionar qualquer coisa
          >>> print c
          Counter({’f’: ’asdad’, ’a’: 3, ’b’: 2, ’d’: 2, ’c’: 1})
          >>> c[’f’] > c[’a’]
          True

          >>> c.update([’a’, ’b’, ’b’, ’d’])
          # c.subtract(iterable-or-mapping) faz o subtracao de elementos
          >>> print c
          Counter({’f’: ’asdad’, ’a’: 4, ’b’: 4, ’d’: 3, ’c’: 1})
Counter


          >>> c = Counter([’a’, ’b’, ’c’, ’d’, ’a’, ’d’, ’b’])
          >>> print c
          Counter({’a’: 2, ’b’: 2, ’d’: 2, ’c’: 1})

          # Funciona como um dicionario
          >>> print c[’a’]
          2
          >>> c[’a’] += 1
          >>> print c
          Counter({’a’: 3, ’b’: 2, ’d’: 2, ’c’: 1})

          >>> print c[’e’] # Retorna 0 ao inves de levantar KeyError
          0

          >>> c.most_common(3)
          [(’a’, 3), (’b’, 2), (’d’, 2)]
          >>> c[’f’] = ’asdad’ # Pode adicionar qualquer coisa
          >>> print c
          Counter({’f’: ’asdad’, ’a’: 3, ’b’: 2, ’d’: 2, ’c’: 1})
          >>> c[’f’] > c[’a’]
          True

          >>> c.update([’a’, ’b’, ’b’, ’d’])
          # c.subtract(iterable-or-mapping) faz o subtracao de elementos
          >>> print c
          Counter({’f’: ’asdad’, ’a’: 4, ’b’: 4, ’d’: 3, ’c’: 1})
Counter


          >>> c = Counter([’a’, ’b’, ’c’, ’d’, ’a’, ’d’, ’b’])
          >>> print c
          Counter({’a’: 2, ’b’: 2, ’d’: 2, ’c’: 1})

          # Funciona como um dicionario
          >>> print c[’a’]
          2
          >>> c[’a’] += 1
          >>> print c
          Counter({’a’: 3, ’b’: 2, ’d’: 2, ’c’: 1})

          >>> print c[’e’] # Retorna 0 ao inves de levantar KeyError
          0

          >>> c.most_common(3)
          [(’a’, 3), (’b’, 2), (’d’, 2)]
          >>> c[’f’] = ’asdad’ # Pode adicionar qualquer coisa
          >>> print c
          Counter({’f’: ’asdad’, ’a’: 3, ’b’: 2, ’d’: 2, ’c’: 1})
          >>> c[’f’] > c[’a’]
          True

          >>> c.update([’a’, ’b’, ’b’, ’d’])
          # c.subtract(iterable-or-mapping) faz o subtracao de elementos
          >>> print c
          Counter({’f’: ’asdad’, ’a’: 4, ’b’: 4, ’d’: 3, ’c’: 1})
Counter


          >>> c = Counter([’a’, ’b’, ’c’, ’d’, ’a’, ’d’, ’b’])
          >>> print c
          Counter({’a’: 2, ’b’: 2, ’d’: 2, ’c’: 1})

          # Funciona como um dicionario
          >>> print c[’a’]
          2
          >>> c[’a’] += 1
          >>> print c
          Counter({’a’: 3, ’b’: 2, ’d’: 2, ’c’: 1})

          >>> print c[’e’] # Retorna 0 ao inves de levantar KeyError
          0

          >>> c.most_common(3)
          [(’a’, 3), (’b’, 2), (’d’, 2)]
          >>> c[’f’] = ’asdad’ # Pode adicionar qualquer coisa
          >>> print c
          Counter({’f’: ’asdad’, ’a’: 3, ’b’: 2, ’d’: 2, ’c’: 1})
          >>> c[’f’] > c[’a’]
          True

          >>> c.update([’a’, ’b’, ’b’, ’d’])
          # c.subtract(iterable-or-mapping) faz o subtracao de elementos
          >>> print c
          Counter({’f’: ’asdad’, ’a’: 4, ’b’: 4, ’d’: 3, ’c’: 1})
Counter: Exemplo

  import re
  from collections import Counter
  LANGUAGES = [
      "C", "C++", "Java", "PHP", "Ruby", "C#",
      "JavaScript", "Perl", "Python"
  ]

  swear_book = [
      ’shit’, ’piss’, ’fuck’,
      ’cock’, ’motherfucker’,                                    Counter({’C++’: 67, ’Ruby’: 64,
  ]                                                                      ’JavaScript’: 55, ’C’: 39,
                                                                         ’Perl’: 33, ’C#’: 29,
  lang_count = Counter()                                                 ’Java’: 23, ’Python’: 15,
  swear_count = Counter()                                                ’PHP’: 11})
                                                                 Counter({’shit’: 213, ’fuck’: 112,
  for lang in LANGUAGES:                                                 ’piss’: 5, ’cock’: 4,
      with open(’language-commits[’ + lang +                             ’motherfucker’: 2})
                  ’].yml’) as f:
          words = re.findall(’w+’, f.read().lower())
          for fu in words:
              if fu in swear_book:
                  lang_count[lang] += 1
                  swear_count[fu] += 1

  print lang_count
  print swear_count
                            data from: https://github.com/AndrewVos/github-statistics
collections.deque
deque




img: http://www.webreference.com
deque




  • lists são lentas para pop(0) e insert(0, v) --> O(n)
  • deque pop e insert no fim ou no início com O(1)
  • deque não substitui list
deque



  >>> d = deque([1,2,3])
  >>> print d
  deque([1, 2, 3])

  >>> d.append(4)
  >>> print d
  deque([1, 2, 3, 4])        >>> d.rotate(1) # Rotaciona a direita
                             >>> print d
  >>> d.appendleft(5)        deque([9, 1, 3, 7, 8])
  >>> print d
  deque([5, 1, 2, 3, 4])     >>> d = deque([1,2,3], maxlen=3)
                             >>> print d
  >>> d.pop(), d.popleft()   deque([1, 2, 3], maxlen=3)
  (4, 5)                     >>> d.append(4)
  >>> del d[1]               deque([2, 3, 4], maxlen=3)
  >>> print d
  deque([1, 3])

  >>> d.extend([7, 8, 9])
  >>> print d
  deque([1, 3, 7, 8, 9])
deque



  >>> d = deque([1,2,3])
  >>> print d
  deque([1, 2, 3])

  >>> d.append(4)
  >>> print d
  deque([1, 2, 3, 4])        >>> d.rotate(1) # Rotaciona a direita
                             >>> print d
  >>> d.appendleft(5)        deque([9, 1, 3, 7, 8])
  >>> print d
  deque([5, 1, 2, 3, 4])     >>> d = deque([1,2,3], maxlen=3)
                             >>> print d
  >>> d.pop(), d.popleft()   deque([1, 2, 3], maxlen=3)
  (4, 5)                     >>> d.append(4)
  >>> del d[1]               deque([2, 3, 4], maxlen=3)
  >>> print d
  deque([1, 3])

  >>> d.extend([7, 8, 9])
  >>> print d
  deque([1, 3, 7, 8, 9])
deque



  >>> d = deque([1,2,3])
  >>> print d
  deque([1, 2, 3])

  >>> d.append(4)
  >>> print d
  deque([1, 2, 3, 4])        >>> d.rotate(1) # Rotaciona a direita
                             >>> print d
  >>> d.appendleft(5)        deque([9, 1, 3, 7, 8])
  >>> print d
  deque([5, 1, 2, 3, 4])     >>> d = deque([1,2,3], maxlen=3)
                             >>> print d
  >>> d.pop(), d.popleft()   deque([1, 2, 3], maxlen=3)
  (4, 5)                     >>> d.append(4)
  >>> del d[1]               deque([2, 3, 4], maxlen=3)
  >>> print d
  deque([1, 3])

  >>> d.extend([7, 8, 9])
  >>> print d
  deque([1, 3, 7, 8, 9])
deque



  >>> d = deque([1,2,3])
  >>> print d
  deque([1, 2, 3])

  >>> d.append(4)
  >>> print d
  deque([1, 2, 3, 4])        >>> d.rotate(1) # Rotaciona a direita
                             >>> print d
  >>> d.appendleft(5)        deque([9, 1, 3, 7, 8])
  >>> print d
  deque([5, 1, 2, 3, 4])     >>> d = deque([1,2,3], maxlen=3)
                             >>> print d
  >>> d.pop(), d.popleft()   deque([1, 2, 3], maxlen=3)
  (4, 5)                     >>> d.append(4)
  >>> del d[1]               deque([2, 3, 4], maxlen=3)
  >>> print d
  deque([1, 3])

  >>> d.extend([7, 8, 9])
  >>> print d
  deque([1, 3, 7, 8, 9])
deque



  >>> d = deque([1,2,3])
  >>> print d
  deque([1, 2, 3])

  >>> d.append(4)
  >>> print d
  deque([1, 2, 3, 4])        >>> d.rotate(1) # Rotaciona a direita
                             >>> print d
  >>> d.appendleft(5)        deque([9, 1, 3, 7, 8])
  >>> print d
  deque([5, 1, 2, 3, 4])     >>> d = deque([1,2,3], maxlen=3)
                             >>> print d
  >>> d.pop(), d.popleft()   deque([1, 2, 3], maxlen=3)
  (4, 5)                     >>> d.append(4)
  >>> del d[1]               deque([2, 3, 4], maxlen=3)
  >>> print d
  deque([1, 3])

  >>> d.extend([7, 8, 9])
  >>> print d
  deque([1, 3, 7, 8, 9])
deque



  >>> d = deque([1,2,3])
  >>> print d
  deque([1, 2, 3])

  >>> d.append(4)
  >>> print d
  deque([1, 2, 3, 4])        >>> d.rotate(1) # Rotaciona a direita
                             >>> print d
  >>> d.appendleft(5)        deque([9, 1, 3, 7, 8])
  >>> print d
  deque([5, 1, 2, 3, 4])     >>> d = deque([1,2,3], maxlen=3)
                             >>> print d
  >>> d.pop(), d.popleft()   deque([1, 2, 3], maxlen=3)
  (4, 5)                     >>> d.append(4)
  >>> del d[1]               deque([2, 3, 4], maxlen=3)
  >>> print d
  deque([1, 3])

  >>> d.extend([7, 8, 9])
  >>> print d
  deque([1, 3, 7, 8, 9])
deque



  >>> d = deque([1,2,3])
  >>> print d
  deque([1, 2, 3])

  >>> d.append(4)
  >>> print d
  deque([1, 2, 3, 4])        >>> d.rotate(1) # Rotaciona a direita
                             >>> print d
  >>> d.appendleft(5)        deque([9, 1, 3, 7, 8])
  >>> print d
  deque([5, 1, 2, 3, 4])     >>> d = deque([1,2,3], maxlen=3)
                             >>> print d
  >>> d.pop(), d.popleft()   deque([1, 2, 3], maxlen=3)
  (4, 5)                     >>> d.append(4)
  >>> del d[1]               deque([2, 3, 4], maxlen=3)
  >>> print d
  deque([1, 3])

  >>> d.extend([7, 8, 9])
  >>> print d
  deque([1, 3, 7, 8, 9])
deque vs list


   num =   100000
   print   u"Tempo para insercao no inicio:"
   print   "Deque:",
   print   timeit.Timer(’dq.appendleft("abc")’,
                         ’from collections import deque;’+
                        ’dq = deque()’).timeit(number=num)
   print   "List:",
   print   timeit.Timer(’li.insert(0, "abc")’,
                         ’li =[]’).timeit(number=num)       Tempo para insercao no inicio:
   print   "Tempo para pop(0):"                             Deque: 0.0206291675568
   print   "Deque:",                                        List: 5.03016710281
   print   timeit.Timer(’dq.popleft()’,                     ----------
                       ’from collections import deque;’+    Tempo para pop(0):
                        ’dq = deque(range(%i))’ % num       Deque: 0.0202388763428
                       ).timeit(number=num)                 List: 3.49450302124
   print   "List:",                                         ----------
   print   timeit.Timer(’li.pop(0)’,                        Tempo de acesso ao meio:
                         ’li = range(%i)’ % num             Deque: 4.97369003296
                       ).timeit(number=num)                 List: 0.051794052124
   print   "Tempo de acesso ao meio:"
   print   "Deque:",
   print   timeit.Timer(’dq[meio]’, ’from collections import deque;’+
                                    ’dq = deque(range(%i));’ % num +
                                    ’meio = len(dq)/2’).timeit()
   print   "List:",
   print   timeit.Timer(’li[meio]’, ’li = range(%i);’ % num +
                                    ’meio = len(li)/2’).timeit()
collections.namedtuple
namedtuple



             >>> Point = namedtuple(’Point’, [’x’, ’y’])
             >>> p = Point(2, 3)
             >>> print p.x, p.y
             2 3

             >>> print p[0:2]
             (2, 3)
             >>> print p.count(2) # herda metodos de tuple
             1

             >>> Point._make([1,2])
             Point(x=1, y=2)

             >>> p._asdict()
             OrderedDict([(’x’, 2), (’y’, 3)])

             >>> p._replace(x=77)
             Point(x=77, y=3)

             >>> p._fields
             (’x’, ’y’)
namedtuple



             >>> Point = namedtuple(’Point’, [’x’, ’y’])
             >>> p = Point(2, 3)
             >>> print p.x, p.y
             2 3

             >>> print p[0:2]
             (2, 3)
             >>> print p.count(2) # herda metodos de tuple
             1

             >>> Point._make([1,2])
             Point(x=1, y=2)

             >>> p._asdict()
             OrderedDict([(’x’, 2), (’y’, 3)])

             >>> p._replace(x=77)
             Point(x=77, y=3)

             >>> p._fields
             (’x’, ’y’)
namedtuple



             >>> Point = namedtuple(’Point’, [’x’, ’y’])
             >>> p = Point(2, 3)
             >>> print p.x, p.y
             2 3

             >>> print p[0:2]
             (2, 3)
             >>> print p.count(2) # herda metodos de tuple
             1

             >>> Point._make([1,2])
             Point(x=1, y=2)

             >>> p._asdict()
             OrderedDict([(’x’, 2), (’y’, 3)])

             >>> p._replace(x=77)
             Point(x=77, y=3)

             >>> p._fields
             (’x’, ’y’)
namedtuple



             >>> Point = namedtuple(’Point’, [’x’, ’y’])
             >>> p = Point(2, 3)
             >>> print p.x, p.y
             2 3

             >>> print p[0:2]
             (2, 3)
             >>> print p.count(2) # herda metodos de tuple
             1

             >>> Point._make([1,2])
             Point(x=1, y=2)

             >>> p._asdict()
             OrderedDict([(’x’, 2), (’y’, 3)])

             >>> p._replace(x=77)
             Point(x=77, y=3)

             >>> p._fields
             (’x’, ’y’)
namedtuple



             >>> Point = namedtuple(’Point’, [’x’, ’y’])
             >>> p = Point(2, 3)
             >>> print p.x, p.y
             2 3

             >>> print p[0:2]
             (2, 3)
             >>> print p.count(2) # herda metodos de tuple
             1

             >>> Point._make([1,2])
             Point(x=1, y=2)

             >>> p._asdict()
             OrderedDict([(’x’, 2), (’y’, 3)])

             >>> p._replace(x=77)
             Point(x=77, y=3)

             >>> p._fields
             (’x’, ’y’)
namedtuple



             >>> Point = namedtuple(’Point’, [’x’, ’y’])
             >>> p = Point(2, 3)
             >>> print p.x, p.y
             2 3

             >>> print p[0:2]
             (2, 3)
             >>> print p.count(2) # herda metodos de tuple
             1

             >>> Point._make([1,2])
             Point(x=1, y=2)

             >>> p._asdict()
             OrderedDict([(’x’, 2), (’y’, 3)])

             >>> p._replace(x=77)
             Point(x=77, y=3)

             >>> p._fields
             (’x’, ’y’)
collections.OrderedDict
OrderedDict




              >>> d = {’banana’: 3, ’apple’:4, ’pear’: 1, ’orange’: 2}
              >>> print d
              {’orange’: 2, ’pear’: 1, ’banana’: 3, ’apple’: 4}

              >>> print OrderedDict(sorted(d.items()))
              OrderedDict([(’apple’, 4), (’banana’, 3), (’orange’, 2), (’pear’, 1)])

              >>> od = OrderedDict(sorted(d.items(), key=lambda k: k[1]))
              >>> print od
              OrderedDict([(’pear’, 1), (’orange’, 2), (’banana’, 3), (’apple’, 4)])

              >>> od.popitem()
              (’apple’, 4)
              >>> print od
              OrderedDict([(’pear’, 1), (’orange’, 2), (’banana’, 3)])
OrderedDict




              >>> d = {’banana’: 3, ’apple’:4, ’pear’: 1, ’orange’: 2}
              >>> print d
              {’orange’: 2, ’pear’: 1, ’banana’: 3, ’apple’: 4}

              >>> print OrderedDict(sorted(d.items()))
              OrderedDict([(’apple’, 4), (’banana’, 3), (’orange’, 2), (’pear’, 1)])

              >>> od = OrderedDict(sorted(d.items(), key=lambda k: k[1]))
              >>> print od
              OrderedDict([(’pear’, 1), (’orange’, 2), (’banana’, 3), (’apple’, 4)])

              >>> od.popitem()
              (’apple’, 4)
              >>> print od
              OrderedDict([(’pear’, 1), (’orange’, 2), (’banana’, 3)])
OrderedDict




              >>> d = {’banana’: 3, ’apple’:4, ’pear’: 1, ’orange’: 2}
              >>> print d
              {’orange’: 2, ’pear’: 1, ’banana’: 3, ’apple’: 4}

              >>> print OrderedDict(sorted(d.items()))
              OrderedDict([(’apple’, 4), (’banana’, 3), (’orange’, 2), (’pear’, 1)])

              >>> od = OrderedDict(sorted(d.items(), key=lambda k: k[1]))
              >>> print od
              OrderedDict([(’pear’, 1), (’orange’, 2), (’banana’, 3), (’apple’, 4)])

              >>> od.popitem()
              (’apple’, 4)
              >>> print od
              OrderedDict([(’pear’, 1), (’orange’, 2), (’banana’, 3)])
OrderedDict




              >>> d = {’banana’: 3, ’apple’:4, ’pear’: 1, ’orange’: 2}
              >>> print d
              {’orange’: 2, ’pear’: 1, ’banana’: 3, ’apple’: 4}

              >>> print OrderedDict(sorted(d.items()))
              OrderedDict([(’apple’, 4), (’banana’, 3), (’orange’, 2), (’pear’, 1)])

              >>> od = OrderedDict(sorted(d.items(), key=lambda k: k[1]))
              >>> print od
              OrderedDict([(’pear’, 1), (’orange’, 2), (’banana’, 3), (’apple’, 4)])

              >>> od.popitem()
              (’apple’, 4)
              >>> print od
              OrderedDict([(’pear’, 1), (’orange’, 2), (’banana’, 3)])
collections.abc
  ABC - Abstract Base Class
abc em 2 minutos



            class AbstractKnight(object):

               __metaclass__ = abc.ABCMeta
               @abc.abstractmethod
               def echo(self):
                   pass

            class IncompKnight(AbstractKnight):
                pass

            >>> IncompKnight()
            TypeError: Can’t instantiate abstract class IncompKnight
            with abstract methods echo

            >>> AbstractKnight.__abstractmethods__
            frozenset([’echo’])

            class KnightImp(AbstractKnight):
                def echo(self):
                    print ’Ni’
            >>> KnightImp().echo()
            Ni
abc em 2 minutos



            class AbstractKnight(object):

               __metaclass__ = abc.ABCMeta
               @abc.abstractmethod
               def echo(self):
                   pass

            class IncompKnight(AbstractKnight):
                pass

            >>> IncompKnight()
            TypeError: Can’t instantiate abstract class IncompKnight
            with abstract methods echo

            >>> AbstractKnight.__abstractmethods__
            frozenset([’echo’])

            class KnightImp(AbstractKnight):
                def echo(self):
                    print ’Ni’
            >>> KnightImp().echo()
            Ni
abc em 2 minutos



            class AbstractKnight(object):

               __metaclass__ = abc.ABCMeta
               @abc.abstractmethod
               def echo(self):
                   pass

            class IncompKnight(AbstractKnight):
                pass

            >>> IncompKnight()
            TypeError: Can’t instantiate abstract class IncompKnight
            with abstract methods echo

            >>> AbstractKnight.__abstractmethods__
            frozenset([’echo’])

            class KnightImp(AbstractKnight):
                def echo(self):
                    print ’Ni’
            >>> KnightImp().echo()
            Ni
abc em 2 minutos



            class AbstractKnight(object):

               __metaclass__ = abc.ABCMeta
               @abc.abstractmethod
               def echo(self):
                   pass

            class IncompKnight(AbstractKnight):
                pass

            >>> IncompKnight()
            TypeError: Can’t instantiate abstract class IncompKnight
            with abstract methods echo

            >>> AbstractKnight.__abstractmethods__
            frozenset([’echo’])

            class KnightImp(AbstractKnight):
                def echo(self):
                    print ’Ni’
            >>> KnightImp().echo()
            Ni
abc em 2 minutos



            class AbstractKnight(object):

               __metaclass__ = abc.ABCMeta
               @abc.abstractmethod
               def echo(self):
                   pass

            class IncompKnight(AbstractKnight):
                pass

            >>> IncompKnight()
            TypeError: Can’t instantiate abstract class IncompKnight
            with abstract methods echo

            >>> AbstractKnight.__abstractmethods__
            frozenset([’echo’])

            class KnightImp(AbstractKnight):
                def echo(self):
                    print ’Ni’
            >>> KnightImp().echo()
            Ni
Herdando dict




            class Dicto(dict):
                def __getitem__(self, k):
                    return 31

            >>> d = Dicto()
            >>> d[2]
            31

            >>> print d.get(2)
            None

            D’oh : (
Herdando dict




            class Dicto(dict):
                def __getitem__(self, k):
                    return 31

            >>> d = Dicto()
            >>> d[2]
            31

            >>> print d.get(2)
            None

            D’oh : (
Herdando dict




            class Dicto(dict):
                def __getitem__(self, k):
                    return 31

            >>> d = Dicto()
            >>> d[2]
            31

            >>> print d.get(2)
            None

            D’oh : (
collections.abc




   • subclasses de builtin containers nem sempre produzem resultados
    esperados
   • subclasses de ABC produzem
collections.abc
if you’re lazy



                                                    Callable -> [’__call__’]
                                                    Container -> [’__contains__’]
                                                    Hashable -> [’__hash__’]
                                                    ItemsView -> []
                                                    Iterable -> [’__iter__’]
     # ex: MutableMapping.__abstractmethods__       Iterator -> [’next’]
     for i in dir(collections):                     KeysView -> []
         try:                                       Mapping -> [’__iter__’, ’__getitem__’, ’__len__’]
              meths = list(getattr(collections, i   MappingView -> []
                          ).__abstractmethods__)    MutableMapping -> [’__delitem__’, ’__setitem__’,
              print i, ’->’, meths                                   ’__getitem__’, ’__iter__’, ’__len__’]
         except:                                    MutableSequence -> [’__delitem__’, ’__setitem__’,
              pass                                                   ’__getitem__’, ’__len__’, ’insert’]
                                                    MutableSet -> [’discard’, ’add’, ’__iter__’,
                                                                     ’__len__’, ’__contains__’]
                                                    Sequence -> [’__getitem__’, ’__len__’]
                                                    Set -> [’__iter__’, ’__len__’, ’__contains__’]
                                                    Sized -> [’__len__’]
                                                    ValuesView -> []
Subclassing dict de
collections.MutableMapping


    from collections import MutableMapping

    class Dicto(MutableMapping):

       def __init__(self):
           self.d = {}                       >>> d = Dicto()
                                             >>> d[’eggs’] = ’ovos’
       def __delitem__(self, i):             >>> d[’ham’] = ’presunto’
           del self.d[i]                     >>> for i in d:
                                             ...    print i + ’:’ + d[i]
       def __setitem__(self, k, v):          eggs:ovos
           self.d[k.lower()] = v             ham:presunto
                                             >>> d.get(’HaM’)
       def __getitem__(self, k):             presunto
           return self.d[k.lower()]          >>> d[’eGGs’]
                                             ’ovos’
       def __iter__(self):
           return iter(self.d)

       def __len__(self):
           return len(self.d)
Subclassing dict de
collections.MutableMapping


    from collections import MutableMapping

    class Dicto(MutableMapping):

       def __init__(self):
           self.d = {}                       >>> d = Dicto()
                                             >>> d[’eggs’] = ’ovos’
       def __delitem__(self, i):             >>> d[’ham’] = ’presunto’
           del self.d[i]                     >>> for i in d:
                                             ...    print i + ’:’ + d[i]
       def __setitem__(self, k, v):          eggs:ovos
           self.d[k.lower()] = v             ham:presunto
                                             >>> d.get(’HaM’)
       def __getitem__(self, k):             presunto
           return self.d[k.lower()]          >>> d[’eGGs’]
                                             ’ovos’
       def __iter__(self):
           return iter(self.d)

       def __len__(self):
           return len(self.d)
Referência


  • Lightning Talk de:




    no fisl 2011.
  • The Data Structures of Python, Alex Gaynor no PyCon2011
  • http://www.doughellmann.com/PyMOTW/abc/index.html
  • http://docs.python.org/library/collections.html
Dúvidas?




                     André Ericson
           http://www.github.com/aericson
                de.ericson@gmail.com
                      @_aericson

Contenu connexe

Tendances

令和から本気出す
令和から本気出す令和から本気出す
令和から本気出すTakashi Kitano
 
python高级内存管理
python高级内存管理python高级内存管理
python高级内存管理rfyiamcool
 
{tidygraph}と{ggraph}による モダンなネットワーク分析(未公開ver)
{tidygraph}と{ggraph}による モダンなネットワーク分析(未公開ver){tidygraph}と{ggraph}による モダンなネットワーク分析(未公開ver)
{tidygraph}と{ggraph}による モダンなネットワーク分析(未公開ver)Takashi Kitano
 
The groovy puzzlers (as Presented at JavaOne 2014)
The groovy puzzlers (as Presented at JavaOne 2014)The groovy puzzlers (as Presented at JavaOne 2014)
The groovy puzzlers (as Presented at JavaOne 2014)GroovyPuzzlers
 
밑바닥부터 시작하는 의료 AI
밑바닥부터 시작하는 의료 AI밑바닥부터 시작하는 의료 AI
밑바닥부터 시작하는 의료 AINAVER Engineering
 
Taking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order FunctionsTaking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order FunctionsDavid Golden
 
{shiny}と{leaflet}による地図アプリ開発Tips
{shiny}と{leaflet}による地図アプリ開発Tips{shiny}と{leaflet}による地図アプリ開発Tips
{shiny}と{leaflet}による地図アプリ開発TipsTakashi Kitano
 
An Elephant of a Different Colour: Hack
An Elephant of a Different Colour: HackAn Elephant of a Different Colour: Hack
An Elephant of a Different Colour: HackVic Metcalfe
 
ggplot2 extensions-ggtree.
ggplot2 extensions-ggtree.ggplot2 extensions-ggtree.
ggplot2 extensions-ggtree.Dr. Volkan OBAN
 
Groovy collection api
Groovy collection apiGroovy collection api
Groovy collection apitrygvea
 
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲Mohammad Reza Kamalifard
 
Intro to OTP in Elixir
Intro to OTP in ElixirIntro to OTP in Elixir
Intro to OTP in ElixirJesse Anderson
 
Functional Pe(a)rls - the Purely Functional Datastructures edition
Functional Pe(a)rls - the Purely Functional Datastructures editionFunctional Pe(a)rls - the Purely Functional Datastructures edition
Functional Pe(a)rls - the Purely Functional Datastructures editionosfameron
 
Python for High School Programmers
Python for High School ProgrammersPython for High School Programmers
Python for High School ProgrammersSiva Arunachalam
 

Tendances (20)

令和から本気出す
令和から本気出す令和から本気出す
令和から本気出す
 
Codigos
CodigosCodigos
Codigos
 
python高级内存管理
python高级内存管理python高级内存管理
python高级内存管理
 
{tidygraph}と{ggraph}による モダンなネットワーク分析(未公開ver)
{tidygraph}と{ggraph}による モダンなネットワーク分析(未公開ver){tidygraph}と{ggraph}による モダンなネットワーク分析(未公開ver)
{tidygraph}と{ggraph}による モダンなネットワーク分析(未公開ver)
 
The groovy puzzlers (as Presented at JavaOne 2014)
The groovy puzzlers (as Presented at JavaOne 2014)The groovy puzzlers (as Presented at JavaOne 2014)
The groovy puzzlers (as Presented at JavaOne 2014)
 
밑바닥부터 시작하는 의료 AI
밑바닥부터 시작하는 의료 AI밑바닥부터 시작하는 의료 AI
밑바닥부터 시작하는 의료 AI
 
Five
FiveFive
Five
 
Slides
SlidesSlides
Slides
 
Taking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order FunctionsTaking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order Functions
 
{shiny}と{leaflet}による地図アプリ開発Tips
{shiny}と{leaflet}による地図アプリ開発Tips{shiny}と{leaflet}による地図アプリ開発Tips
{shiny}と{leaflet}による地図アプリ開発Tips
 
Lập trình Python cơ bản
Lập trình Python cơ bảnLập trình Python cơ bản
Lập trình Python cơ bản
 
An Elephant of a Different Colour: Hack
An Elephant of a Different Colour: HackAn Elephant of a Different Colour: Hack
An Elephant of a Different Colour: Hack
 
ggplot2 extensions-ggtree.
ggplot2 extensions-ggtree.ggplot2 extensions-ggtree.
ggplot2 extensions-ggtree.
 
Groovy collection api
Groovy collection apiGroovy collection api
Groovy collection api
 
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
 
Intro
IntroIntro
Intro
 
Intro to OTP in Elixir
Intro to OTP in ElixirIntro to OTP in Elixir
Intro to OTP in Elixir
 
Functional Pe(a)rls - the Purely Functional Datastructures edition
Functional Pe(a)rls - the Purely Functional Datastructures editionFunctional Pe(a)rls - the Purely Functional Datastructures edition
Functional Pe(a)rls - the Purely Functional Datastructures edition
 
Python for High School Programmers
Python for High School ProgrammersPython for High School Programmers
Python for High School Programmers
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 

En vedette

Apresentando o I Toró de Palestras do PUG-PE
Apresentando o I Toró de Palestras do PUG-PEApresentando o I Toró de Palestras do PUG-PE
Apresentando o I Toró de Palestras do PUG-PEMarcel Caraciolo
 
Pyjamas: Uma Ferramenta Pythônica para Web
Pyjamas: Uma Ferramenta Pythônica para WebPyjamas: Uma Ferramenta Pythônica para Web
Pyjamas: Uma Ferramenta Pythônica para WebNielson Santana
 
Coding Dojo e Test Driven Development
Coding Dojo e Test Driven DevelopmentCoding Dojo e Test Driven Development
Coding Dojo e Test Driven Developmentpugpe
 
Python na formacao_de_jovens
Python na formacao_de_jovensPython na formacao_de_jovens
Python na formacao_de_jovensMarcos Egito
 
Peça seu código em casamento: Votos, Tópicos e TDD
Peça seu código em casamento: Votos, Tópicos e TDDPeça seu código em casamento: Votos, Tópicos e TDD
Peça seu código em casamento: Votos, Tópicos e TDDRafael Carício
 
Python e Cadeias de Markov GHMM
Python e Cadeias de Markov GHMMPython e Cadeias de Markov GHMM
Python e Cadeias de Markov GHMMpugpe
 
(entregando djangoapps)@tangerinalab - pugpe xv
(entregando djangoapps)@tangerinalab - pugpe xv(entregando djangoapps)@tangerinalab - pugpe xv
(entregando djangoapps)@tangerinalab - pugpe xvraonyaraujo
 
Rain Toolbox - Previsão de Chuvas
Rain Toolbox -  Previsão de ChuvasRain Toolbox -  Previsão de Chuvas
Rain Toolbox - Previsão de Chuvaspugpe
 
Blender Com Python
Blender Com PythonBlender Com Python
Blender Com Pythonpugpe
 
Criando comunidades bem sucedidas
Criando comunidades bem sucedidasCriando comunidades bem sucedidas
Criando comunidades bem sucedidaspugpe
 
Wikilytics
WikilyticsWikilytics
Wikilyticspugpe
 
Computação Científica com Python
Computação Científica com PythonComputação Científica com Python
Computação Científica com PythonHugo Serrano
 
Migrando do App Engine para o Heroku
Migrando do App Engine para o HerokuMigrando do App Engine para o Heroku
Migrando do App Engine para o HerokuFilipe Ximenes
 
Qml + Python
Qml + PythonQml + Python
Qml + Pythonpugpe
 
NoSQL com Cassandra e Python
NoSQL com Cassandra e PythonNoSQL com Cassandra e Python
NoSQL com Cassandra e Pythonpugpe
 
Palestra sobre Inteligência Coletiva
Palestra sobre Inteligência ColetivaPalestra sobre Inteligência Coletiva
Palestra sobre Inteligência Coletivapugpe
 

En vedette (20)

Apresentando o I Toró de Palestras do PUG-PE
Apresentando o I Toró de Palestras do PUG-PEApresentando o I Toró de Palestras do PUG-PE
Apresentando o I Toró de Palestras do PUG-PE
 
Pyjamas: Uma Ferramenta Pythônica para Web
Pyjamas: Uma Ferramenta Pythônica para WebPyjamas: Uma Ferramenta Pythônica para Web
Pyjamas: Uma Ferramenta Pythônica para Web
 
Coding Dojo e Test Driven Development
Coding Dojo e Test Driven DevelopmentCoding Dojo e Test Driven Development
Coding Dojo e Test Driven Development
 
Python na formacao_de_jovens
Python na formacao_de_jovensPython na formacao_de_jovens
Python na formacao_de_jovens
 
Peça seu código em casamento: Votos, Tópicos e TDD
Peça seu código em casamento: Votos, Tópicos e TDDPeça seu código em casamento: Votos, Tópicos e TDD
Peça seu código em casamento: Votos, Tópicos e TDD
 
Python e Cadeias de Markov GHMM
Python e Cadeias de Markov GHMMPython e Cadeias de Markov GHMM
Python e Cadeias de Markov GHMM
 
(entregando djangoapps)@tangerinalab - pugpe xv
(entregando djangoapps)@tangerinalab - pugpe xv(entregando djangoapps)@tangerinalab - pugpe xv
(entregando djangoapps)@tangerinalab - pugpe xv
 
Pep 8
Pep 8Pep 8
Pep 8
 
Rain Toolbox - Previsão de Chuvas
Rain Toolbox -  Previsão de ChuvasRain Toolbox -  Previsão de Chuvas
Rain Toolbox - Previsão de Chuvas
 
Blender Com Python
Blender Com PythonBlender Com Python
Blender Com Python
 
Criando comunidades bem sucedidas
Criando comunidades bem sucedidasCriando comunidades bem sucedidas
Criando comunidades bem sucedidas
 
Wikilytics
WikilyticsWikilytics
Wikilytics
 
Computação Científica com Python
Computação Científica com PythonComputação Científica com Python
Computação Científica com Python
 
Migrando do App Engine para o Heroku
Migrando do App Engine para o HerokuMigrando do App Engine para o Heroku
Migrando do App Engine para o Heroku
 
Qml + Python
Qml + PythonQml + Python
Qml + Python
 
Pug
PugPug
Pug
 
Arduino e python
Arduino e pythonArduino e python
Arduino e python
 
NoSQL com Cassandra e Python
NoSQL com Cassandra e PythonNoSQL com Cassandra e Python
NoSQL com Cassandra e Python
 
Palestra sobre Inteligência Coletiva
Palestra sobre Inteligência ColetivaPalestra sobre Inteligência Coletiva
Palestra sobre Inteligência Coletiva
 
REST APIs com Django
REST APIs com DjangoREST APIs com Django
REST APIs com Django
 

Similaire à Palestra sobre Collections com Python

Τα Πολύ Βασικά για την Python
Τα Πολύ Βασικά για την PythonΤα Πολύ Βασικά για την Python
Τα Πολύ Βασικά για την PythonMoses Boudourides
 
Useful javascript
Useful javascriptUseful javascript
Useful javascriptLei Kang
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7decoupled
 
Functions in python
Functions in pythonFunctions in python
Functions in pythonIlian Iliev
 
Beautiful python - PyLadies
Beautiful python - PyLadiesBeautiful python - PyLadies
Beautiful python - PyLadiesAlicia Pérez
 
Extending Operators in Perl with Operator::Util
Extending Operators in Perl with Operator::UtilExtending Operators in Perl with Operator::Util
Extending Operators in Perl with Operator::UtilNova Patch
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Paige Bailey
 
Python 표준 라이브러리
Python 표준 라이브러리Python 표준 라이브러리
Python 표준 라이브러리용 최
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesMatt Harrison
 
[1062BPY12001] Data analysis with R / week 2
[1062BPY12001] Data analysis with R / week 2[1062BPY12001] Data analysis with R / week 2
[1062BPY12001] Data analysis with R / week 2Kevin Chun-Hsien Hsu
 
Python 내장 함수
Python 내장 함수Python 내장 함수
Python 내장 함수용 최
 
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)MongoSF
 
Optimization and Mathematical Programming in R and ROI - R Optimization Infra...
Optimization and Mathematical Programming in R and ROI - R Optimization Infra...Optimization and Mathematical Programming in R and ROI - R Optimization Infra...
Optimization and Mathematical Programming in R and ROI - R Optimization Infra...Dr. Volkan OBAN
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxMihirDatir
 

Similaire à Palestra sobre Collections com Python (20)

Τα Πολύ Βασικά για την Python
Τα Πολύ Βασικά για την PythonΤα Πολύ Βασικά για την Python
Τα Πολύ Βασικά για την Python
 
Useful javascript
Useful javascriptUseful javascript
Useful javascript
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
 
Python 1
Python 1Python 1
Python 1
 
R programming language
R programming languageR programming language
R programming language
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Beautiful python - PyLadies
Beautiful python - PyLadiesBeautiful python - PyLadies
Beautiful python - PyLadies
 
Extending Operators in Perl with Operator::Util
Extending Operators in Perl with Operator::UtilExtending Operators in Perl with Operator::Util
Extending Operators in Perl with Operator::Util
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!
 
Python 표준 라이브러리
Python 표준 라이브러리Python 표준 라이브러리
Python 표준 라이브러리
 
dplyr
dplyrdplyr
dplyr
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
[1062BPY12001] Data analysis with R / week 2
[1062BPY12001] Data analysis with R / week 2[1062BPY12001] Data analysis with R / week 2
[1062BPY12001] Data analysis with R / week 2
 
R programming
R programmingR programming
R programming
 
Python 내장 함수
Python 내장 함수Python 내장 함수
Python 내장 함수
 
Python course Day 1
Python course Day 1Python course Day 1
Python course Day 1
 
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
 
Optimization and Mathematical Programming in R and ROI - R Optimization Infra...
Optimization and Mathematical Programming in R and ROI - R Optimization Infra...Optimization and Mathematical Programming in R and ROI - R Optimization Infra...
Optimization and Mathematical Programming in R and ROI - R Optimization Infra...
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptx
 

Plus de pugpe

Projeto Amadeus
Projeto AmadeusProjeto Amadeus
Projeto Amadeuspugpe
 
E o que danado é o PUG-PE?
E o que danado é o PUG-PE?E o que danado é o PUG-PE?
E o que danado é o PUG-PE?pugpe
 
Intro
IntroIntro
Intropugpe
 
Construindo uma startup em 54 horas com Python
Construindo uma startup em 54 horas com PythonConstruindo uma startup em 54 horas com Python
Construindo uma startup em 54 horas com Pythonpugpe
 
Automatizando tarefas com Python
Automatizando tarefas com PythonAutomatizando tarefas com Python
Automatizando tarefas com Pythonpugpe
 
Visualização da Informação
Visualização da InformaçãoVisualização da Informação
Visualização da Informaçãopugpe
 
Desenvolvendo aplicativos web com o google app engine
Desenvolvendo aplicativos web com o google app engineDesenvolvendo aplicativos web com o google app engine
Desenvolvendo aplicativos web com o google app enginepugpe
 
Pip - Instalando Pacotes facilmente para Python
Pip - Instalando Pacotes facilmente para PythonPip - Instalando Pacotes facilmente para Python
Pip - Instalando Pacotes facilmente para Pythonpugpe
 
Pug pe vii - luciano rodrigues - debugger
Pug pe vii - luciano rodrigues - debuggerPug pe vii - luciano rodrigues - debugger
Pug pe vii - luciano rodrigues - debuggerpugpe
 
Pug pe viii - luciano rodrigues - debugger
Pug pe viii - luciano rodrigues - debuggerPug pe viii - luciano rodrigues - debugger
Pug pe viii - luciano rodrigues - debuggerpugpe
 
Python e Django
Python e DjangoPython e Django
Python e Djangopugpe
 
Python e Dispositivos Móveis
Python e Dispositivos MóveisPython e Dispositivos Móveis
Python e Dispositivos Móveispugpe
 
Redes Neurais e Python
Redes Neurais e PythonRedes Neurais e Python
Redes Neurais e Pythonpugpe
 
CATS: Sistema de Recomendação de Eventos
CATS: Sistema de Recomendação de EventosCATS: Sistema de Recomendação de Eventos
CATS: Sistema de Recomendação de Eventospugpe
 
Python Funcional
Python FuncionalPython Funcional
Python Funcionalpugpe
 
Open Allure
Open AllureOpen Allure
Open Allurepugpe
 
Iron Python
Iron PythonIron Python
Iron Pythonpugpe
 

Plus de pugpe (17)

Projeto Amadeus
Projeto AmadeusProjeto Amadeus
Projeto Amadeus
 
E o que danado é o PUG-PE?
E o que danado é o PUG-PE?E o que danado é o PUG-PE?
E o que danado é o PUG-PE?
 
Intro
IntroIntro
Intro
 
Construindo uma startup em 54 horas com Python
Construindo uma startup em 54 horas com PythonConstruindo uma startup em 54 horas com Python
Construindo uma startup em 54 horas com Python
 
Automatizando tarefas com Python
Automatizando tarefas com PythonAutomatizando tarefas com Python
Automatizando tarefas com Python
 
Visualização da Informação
Visualização da InformaçãoVisualização da Informação
Visualização da Informação
 
Desenvolvendo aplicativos web com o google app engine
Desenvolvendo aplicativos web com o google app engineDesenvolvendo aplicativos web com o google app engine
Desenvolvendo aplicativos web com o google app engine
 
Pip - Instalando Pacotes facilmente para Python
Pip - Instalando Pacotes facilmente para PythonPip - Instalando Pacotes facilmente para Python
Pip - Instalando Pacotes facilmente para Python
 
Pug pe vii - luciano rodrigues - debugger
Pug pe vii - luciano rodrigues - debuggerPug pe vii - luciano rodrigues - debugger
Pug pe vii - luciano rodrigues - debugger
 
Pug pe viii - luciano rodrigues - debugger
Pug pe viii - luciano rodrigues - debuggerPug pe viii - luciano rodrigues - debugger
Pug pe viii - luciano rodrigues - debugger
 
Python e Django
Python e DjangoPython e Django
Python e Django
 
Python e Dispositivos Móveis
Python e Dispositivos MóveisPython e Dispositivos Móveis
Python e Dispositivos Móveis
 
Redes Neurais e Python
Redes Neurais e PythonRedes Neurais e Python
Redes Neurais e Python
 
CATS: Sistema de Recomendação de Eventos
CATS: Sistema de Recomendação de EventosCATS: Sistema de Recomendação de Eventos
CATS: Sistema de Recomendação de Eventos
 
Python Funcional
Python FuncionalPython Funcional
Python Funcional
 
Open Allure
Open AllureOpen Allure
Open Allure
 
Iron Python
Iron PythonIron Python
Iron Python
 

Dernier

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 

Dernier (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 

Palestra sobre Collections com Python

  • 2. collections Roteiro • Counter • deque • namedtuple • OrderedDict • abc • collections.abc
  • 4. Counter >>> c = Counter([’a’, ’b’, ’c’, ’d’, ’a’, ’d’, ’b’]) >>> print c Counter({’a’: 2, ’b’: 2, ’d’: 2, ’c’: 1}) # Funciona como um dicionario >>> print c[’a’] 2 >>> c[’a’] += 1 >>> print c Counter({’a’: 3, ’b’: 2, ’d’: 2, ’c’: 1}) >>> print c[’e’] # Retorna 0 ao inves de levantar KeyError 0 >>> c.most_common(3) [(’a’, 3), (’b’, 2), (’d’, 2)] >>> c[’f’] = ’asdad’ # Pode adicionar qualquer coisa >>> print c Counter({’f’: ’asdad’, ’a’: 3, ’b’: 2, ’d’: 2, ’c’: 1}) >>> c[’f’] > c[’a’] True >>> c.update([’a’, ’b’, ’b’, ’d’]) # c.subtract(iterable-or-mapping) faz o subtracao de elementos >>> print c Counter({’f’: ’asdad’, ’a’: 4, ’b’: 4, ’d’: 3, ’c’: 1})
  • 5. Counter >>> c = Counter([’a’, ’b’, ’c’, ’d’, ’a’, ’d’, ’b’]) >>> print c Counter({’a’: 2, ’b’: 2, ’d’: 2, ’c’: 1}) # Funciona como um dicionario >>> print c[’a’] 2 >>> c[’a’] += 1 >>> print c Counter({’a’: 3, ’b’: 2, ’d’: 2, ’c’: 1}) >>> print c[’e’] # Retorna 0 ao inves de levantar KeyError 0 >>> c.most_common(3) [(’a’, 3), (’b’, 2), (’d’, 2)] >>> c[’f’] = ’asdad’ # Pode adicionar qualquer coisa >>> print c Counter({’f’: ’asdad’, ’a’: 3, ’b’: 2, ’d’: 2, ’c’: 1}) >>> c[’f’] > c[’a’] True >>> c.update([’a’, ’b’, ’b’, ’d’]) # c.subtract(iterable-or-mapping) faz o subtracao de elementos >>> print c Counter({’f’: ’asdad’, ’a’: 4, ’b’: 4, ’d’: 3, ’c’: 1})
  • 6. Counter >>> c = Counter([’a’, ’b’, ’c’, ’d’, ’a’, ’d’, ’b’]) >>> print c Counter({’a’: 2, ’b’: 2, ’d’: 2, ’c’: 1}) # Funciona como um dicionario >>> print c[’a’] 2 >>> c[’a’] += 1 >>> print c Counter({’a’: 3, ’b’: 2, ’d’: 2, ’c’: 1}) >>> print c[’e’] # Retorna 0 ao inves de levantar KeyError 0 >>> c.most_common(3) [(’a’, 3), (’b’, 2), (’d’, 2)] >>> c[’f’] = ’asdad’ # Pode adicionar qualquer coisa >>> print c Counter({’f’: ’asdad’, ’a’: 3, ’b’: 2, ’d’: 2, ’c’: 1}) >>> c[’f’] > c[’a’] True >>> c.update([’a’, ’b’, ’b’, ’d’]) # c.subtract(iterable-or-mapping) faz o subtracao de elementos >>> print c Counter({’f’: ’asdad’, ’a’: 4, ’b’: 4, ’d’: 3, ’c’: 1})
  • 7. Counter >>> c = Counter([’a’, ’b’, ’c’, ’d’, ’a’, ’d’, ’b’]) >>> print c Counter({’a’: 2, ’b’: 2, ’d’: 2, ’c’: 1}) # Funciona como um dicionario >>> print c[’a’] 2 >>> c[’a’] += 1 >>> print c Counter({’a’: 3, ’b’: 2, ’d’: 2, ’c’: 1}) >>> print c[’e’] # Retorna 0 ao inves de levantar KeyError 0 >>> c.most_common(3) [(’a’, 3), (’b’, 2), (’d’, 2)] >>> c[’f’] = ’asdad’ # Pode adicionar qualquer coisa >>> print c Counter({’f’: ’asdad’, ’a’: 3, ’b’: 2, ’d’: 2, ’c’: 1}) >>> c[’f’] > c[’a’] True >>> c.update([’a’, ’b’, ’b’, ’d’]) # c.subtract(iterable-or-mapping) faz o subtracao de elementos >>> print c Counter({’f’: ’asdad’, ’a’: 4, ’b’: 4, ’d’: 3, ’c’: 1})
  • 8. Counter >>> c = Counter([’a’, ’b’, ’c’, ’d’, ’a’, ’d’, ’b’]) >>> print c Counter({’a’: 2, ’b’: 2, ’d’: 2, ’c’: 1}) # Funciona como um dicionario >>> print c[’a’] 2 >>> c[’a’] += 1 >>> print c Counter({’a’: 3, ’b’: 2, ’d’: 2, ’c’: 1}) >>> print c[’e’] # Retorna 0 ao inves de levantar KeyError 0 >>> c.most_common(3) [(’a’, 3), (’b’, 2), (’d’, 2)] >>> c[’f’] = ’asdad’ # Pode adicionar qualquer coisa >>> print c Counter({’f’: ’asdad’, ’a’: 3, ’b’: 2, ’d’: 2, ’c’: 1}) >>> c[’f’] > c[’a’] True >>> c.update([’a’, ’b’, ’b’, ’d’]) # c.subtract(iterable-or-mapping) faz o subtracao de elementos >>> print c Counter({’f’: ’asdad’, ’a’: 4, ’b’: 4, ’d’: 3, ’c’: 1})
  • 9. Counter: Exemplo import re from collections import Counter LANGUAGES = [ "C", "C++", "Java", "PHP", "Ruby", "C#", "JavaScript", "Perl", "Python" ] swear_book = [ ’shit’, ’piss’, ’fuck’, ’cock’, ’motherfucker’, Counter({’C++’: 67, ’Ruby’: 64, ] ’JavaScript’: 55, ’C’: 39, ’Perl’: 33, ’C#’: 29, lang_count = Counter() ’Java’: 23, ’Python’: 15, swear_count = Counter() ’PHP’: 11}) Counter({’shit’: 213, ’fuck’: 112, for lang in LANGUAGES: ’piss’: 5, ’cock’: 4, with open(’language-commits[’ + lang + ’motherfucker’: 2}) ’].yml’) as f: words = re.findall(’w+’, f.read().lower()) for fu in words: if fu in swear_book: lang_count[lang] += 1 swear_count[fu] += 1 print lang_count print swear_count data from: https://github.com/AndrewVos/github-statistics
  • 12. deque • lists são lentas para pop(0) e insert(0, v) --> O(n) • deque pop e insert no fim ou no início com O(1) • deque não substitui list
  • 13. deque >>> d = deque([1,2,3]) >>> print d deque([1, 2, 3]) >>> d.append(4) >>> print d deque([1, 2, 3, 4]) >>> d.rotate(1) # Rotaciona a direita >>> print d >>> d.appendleft(5) deque([9, 1, 3, 7, 8]) >>> print d deque([5, 1, 2, 3, 4]) >>> d = deque([1,2,3], maxlen=3) >>> print d >>> d.pop(), d.popleft() deque([1, 2, 3], maxlen=3) (4, 5) >>> d.append(4) >>> del d[1] deque([2, 3, 4], maxlen=3) >>> print d deque([1, 3]) >>> d.extend([7, 8, 9]) >>> print d deque([1, 3, 7, 8, 9])
  • 14. deque >>> d = deque([1,2,3]) >>> print d deque([1, 2, 3]) >>> d.append(4) >>> print d deque([1, 2, 3, 4]) >>> d.rotate(1) # Rotaciona a direita >>> print d >>> d.appendleft(5) deque([9, 1, 3, 7, 8]) >>> print d deque([5, 1, 2, 3, 4]) >>> d = deque([1,2,3], maxlen=3) >>> print d >>> d.pop(), d.popleft() deque([1, 2, 3], maxlen=3) (4, 5) >>> d.append(4) >>> del d[1] deque([2, 3, 4], maxlen=3) >>> print d deque([1, 3]) >>> d.extend([7, 8, 9]) >>> print d deque([1, 3, 7, 8, 9])
  • 15. deque >>> d = deque([1,2,3]) >>> print d deque([1, 2, 3]) >>> d.append(4) >>> print d deque([1, 2, 3, 4]) >>> d.rotate(1) # Rotaciona a direita >>> print d >>> d.appendleft(5) deque([9, 1, 3, 7, 8]) >>> print d deque([5, 1, 2, 3, 4]) >>> d = deque([1,2,3], maxlen=3) >>> print d >>> d.pop(), d.popleft() deque([1, 2, 3], maxlen=3) (4, 5) >>> d.append(4) >>> del d[1] deque([2, 3, 4], maxlen=3) >>> print d deque([1, 3]) >>> d.extend([7, 8, 9]) >>> print d deque([1, 3, 7, 8, 9])
  • 16. deque >>> d = deque([1,2,3]) >>> print d deque([1, 2, 3]) >>> d.append(4) >>> print d deque([1, 2, 3, 4]) >>> d.rotate(1) # Rotaciona a direita >>> print d >>> d.appendleft(5) deque([9, 1, 3, 7, 8]) >>> print d deque([5, 1, 2, 3, 4]) >>> d = deque([1,2,3], maxlen=3) >>> print d >>> d.pop(), d.popleft() deque([1, 2, 3], maxlen=3) (4, 5) >>> d.append(4) >>> del d[1] deque([2, 3, 4], maxlen=3) >>> print d deque([1, 3]) >>> d.extend([7, 8, 9]) >>> print d deque([1, 3, 7, 8, 9])
  • 17. deque >>> d = deque([1,2,3]) >>> print d deque([1, 2, 3]) >>> d.append(4) >>> print d deque([1, 2, 3, 4]) >>> d.rotate(1) # Rotaciona a direita >>> print d >>> d.appendleft(5) deque([9, 1, 3, 7, 8]) >>> print d deque([5, 1, 2, 3, 4]) >>> d = deque([1,2,3], maxlen=3) >>> print d >>> d.pop(), d.popleft() deque([1, 2, 3], maxlen=3) (4, 5) >>> d.append(4) >>> del d[1] deque([2, 3, 4], maxlen=3) >>> print d deque([1, 3]) >>> d.extend([7, 8, 9]) >>> print d deque([1, 3, 7, 8, 9])
  • 18. deque >>> d = deque([1,2,3]) >>> print d deque([1, 2, 3]) >>> d.append(4) >>> print d deque([1, 2, 3, 4]) >>> d.rotate(1) # Rotaciona a direita >>> print d >>> d.appendleft(5) deque([9, 1, 3, 7, 8]) >>> print d deque([5, 1, 2, 3, 4]) >>> d = deque([1,2,3], maxlen=3) >>> print d >>> d.pop(), d.popleft() deque([1, 2, 3], maxlen=3) (4, 5) >>> d.append(4) >>> del d[1] deque([2, 3, 4], maxlen=3) >>> print d deque([1, 3]) >>> d.extend([7, 8, 9]) >>> print d deque([1, 3, 7, 8, 9])
  • 19. deque >>> d = deque([1,2,3]) >>> print d deque([1, 2, 3]) >>> d.append(4) >>> print d deque([1, 2, 3, 4]) >>> d.rotate(1) # Rotaciona a direita >>> print d >>> d.appendleft(5) deque([9, 1, 3, 7, 8]) >>> print d deque([5, 1, 2, 3, 4]) >>> d = deque([1,2,3], maxlen=3) >>> print d >>> d.pop(), d.popleft() deque([1, 2, 3], maxlen=3) (4, 5) >>> d.append(4) >>> del d[1] deque([2, 3, 4], maxlen=3) >>> print d deque([1, 3]) >>> d.extend([7, 8, 9]) >>> print d deque([1, 3, 7, 8, 9])
  • 20. deque vs list num = 100000 print u"Tempo para insercao no inicio:" print "Deque:", print timeit.Timer(’dq.appendleft("abc")’, ’from collections import deque;’+ ’dq = deque()’).timeit(number=num) print "List:", print timeit.Timer(’li.insert(0, "abc")’, ’li =[]’).timeit(number=num) Tempo para insercao no inicio: print "Tempo para pop(0):" Deque: 0.0206291675568 print "Deque:", List: 5.03016710281 print timeit.Timer(’dq.popleft()’, ---------- ’from collections import deque;’+ Tempo para pop(0): ’dq = deque(range(%i))’ % num Deque: 0.0202388763428 ).timeit(number=num) List: 3.49450302124 print "List:", ---------- print timeit.Timer(’li.pop(0)’, Tempo de acesso ao meio: ’li = range(%i)’ % num Deque: 4.97369003296 ).timeit(number=num) List: 0.051794052124 print "Tempo de acesso ao meio:" print "Deque:", print timeit.Timer(’dq[meio]’, ’from collections import deque;’+ ’dq = deque(range(%i));’ % num + ’meio = len(dq)/2’).timeit() print "List:", print timeit.Timer(’li[meio]’, ’li = range(%i);’ % num + ’meio = len(li)/2’).timeit()
  • 22. namedtuple >>> Point = namedtuple(’Point’, [’x’, ’y’]) >>> p = Point(2, 3) >>> print p.x, p.y 2 3 >>> print p[0:2] (2, 3) >>> print p.count(2) # herda metodos de tuple 1 >>> Point._make([1,2]) Point(x=1, y=2) >>> p._asdict() OrderedDict([(’x’, 2), (’y’, 3)]) >>> p._replace(x=77) Point(x=77, y=3) >>> p._fields (’x’, ’y’)
  • 23. namedtuple >>> Point = namedtuple(’Point’, [’x’, ’y’]) >>> p = Point(2, 3) >>> print p.x, p.y 2 3 >>> print p[0:2] (2, 3) >>> print p.count(2) # herda metodos de tuple 1 >>> Point._make([1,2]) Point(x=1, y=2) >>> p._asdict() OrderedDict([(’x’, 2), (’y’, 3)]) >>> p._replace(x=77) Point(x=77, y=3) >>> p._fields (’x’, ’y’)
  • 24. namedtuple >>> Point = namedtuple(’Point’, [’x’, ’y’]) >>> p = Point(2, 3) >>> print p.x, p.y 2 3 >>> print p[0:2] (2, 3) >>> print p.count(2) # herda metodos de tuple 1 >>> Point._make([1,2]) Point(x=1, y=2) >>> p._asdict() OrderedDict([(’x’, 2), (’y’, 3)]) >>> p._replace(x=77) Point(x=77, y=3) >>> p._fields (’x’, ’y’)
  • 25. namedtuple >>> Point = namedtuple(’Point’, [’x’, ’y’]) >>> p = Point(2, 3) >>> print p.x, p.y 2 3 >>> print p[0:2] (2, 3) >>> print p.count(2) # herda metodos de tuple 1 >>> Point._make([1,2]) Point(x=1, y=2) >>> p._asdict() OrderedDict([(’x’, 2), (’y’, 3)]) >>> p._replace(x=77) Point(x=77, y=3) >>> p._fields (’x’, ’y’)
  • 26. namedtuple >>> Point = namedtuple(’Point’, [’x’, ’y’]) >>> p = Point(2, 3) >>> print p.x, p.y 2 3 >>> print p[0:2] (2, 3) >>> print p.count(2) # herda metodos de tuple 1 >>> Point._make([1,2]) Point(x=1, y=2) >>> p._asdict() OrderedDict([(’x’, 2), (’y’, 3)]) >>> p._replace(x=77) Point(x=77, y=3) >>> p._fields (’x’, ’y’)
  • 27. namedtuple >>> Point = namedtuple(’Point’, [’x’, ’y’]) >>> p = Point(2, 3) >>> print p.x, p.y 2 3 >>> print p[0:2] (2, 3) >>> print p.count(2) # herda metodos de tuple 1 >>> Point._make([1,2]) Point(x=1, y=2) >>> p._asdict() OrderedDict([(’x’, 2), (’y’, 3)]) >>> p._replace(x=77) Point(x=77, y=3) >>> p._fields (’x’, ’y’)
  • 29. OrderedDict >>> d = {’banana’: 3, ’apple’:4, ’pear’: 1, ’orange’: 2} >>> print d {’orange’: 2, ’pear’: 1, ’banana’: 3, ’apple’: 4} >>> print OrderedDict(sorted(d.items())) OrderedDict([(’apple’, 4), (’banana’, 3), (’orange’, 2), (’pear’, 1)]) >>> od = OrderedDict(sorted(d.items(), key=lambda k: k[1])) >>> print od OrderedDict([(’pear’, 1), (’orange’, 2), (’banana’, 3), (’apple’, 4)]) >>> od.popitem() (’apple’, 4) >>> print od OrderedDict([(’pear’, 1), (’orange’, 2), (’banana’, 3)])
  • 30. OrderedDict >>> d = {’banana’: 3, ’apple’:4, ’pear’: 1, ’orange’: 2} >>> print d {’orange’: 2, ’pear’: 1, ’banana’: 3, ’apple’: 4} >>> print OrderedDict(sorted(d.items())) OrderedDict([(’apple’, 4), (’banana’, 3), (’orange’, 2), (’pear’, 1)]) >>> od = OrderedDict(sorted(d.items(), key=lambda k: k[1])) >>> print od OrderedDict([(’pear’, 1), (’orange’, 2), (’banana’, 3), (’apple’, 4)]) >>> od.popitem() (’apple’, 4) >>> print od OrderedDict([(’pear’, 1), (’orange’, 2), (’banana’, 3)])
  • 31. OrderedDict >>> d = {’banana’: 3, ’apple’:4, ’pear’: 1, ’orange’: 2} >>> print d {’orange’: 2, ’pear’: 1, ’banana’: 3, ’apple’: 4} >>> print OrderedDict(sorted(d.items())) OrderedDict([(’apple’, 4), (’banana’, 3), (’orange’, 2), (’pear’, 1)]) >>> od = OrderedDict(sorted(d.items(), key=lambda k: k[1])) >>> print od OrderedDict([(’pear’, 1), (’orange’, 2), (’banana’, 3), (’apple’, 4)]) >>> od.popitem() (’apple’, 4) >>> print od OrderedDict([(’pear’, 1), (’orange’, 2), (’banana’, 3)])
  • 32. OrderedDict >>> d = {’banana’: 3, ’apple’:4, ’pear’: 1, ’orange’: 2} >>> print d {’orange’: 2, ’pear’: 1, ’banana’: 3, ’apple’: 4} >>> print OrderedDict(sorted(d.items())) OrderedDict([(’apple’, 4), (’banana’, 3), (’orange’, 2), (’pear’, 1)]) >>> od = OrderedDict(sorted(d.items(), key=lambda k: k[1])) >>> print od OrderedDict([(’pear’, 1), (’orange’, 2), (’banana’, 3), (’apple’, 4)]) >>> od.popitem() (’apple’, 4) >>> print od OrderedDict([(’pear’, 1), (’orange’, 2), (’banana’, 3)])
  • 33. collections.abc ABC - Abstract Base Class
  • 34. abc em 2 minutos class AbstractKnight(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def echo(self): pass class IncompKnight(AbstractKnight): pass >>> IncompKnight() TypeError: Can’t instantiate abstract class IncompKnight with abstract methods echo >>> AbstractKnight.__abstractmethods__ frozenset([’echo’]) class KnightImp(AbstractKnight): def echo(self): print ’Ni’ >>> KnightImp().echo() Ni
  • 35. abc em 2 minutos class AbstractKnight(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def echo(self): pass class IncompKnight(AbstractKnight): pass >>> IncompKnight() TypeError: Can’t instantiate abstract class IncompKnight with abstract methods echo >>> AbstractKnight.__abstractmethods__ frozenset([’echo’]) class KnightImp(AbstractKnight): def echo(self): print ’Ni’ >>> KnightImp().echo() Ni
  • 36. abc em 2 minutos class AbstractKnight(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def echo(self): pass class IncompKnight(AbstractKnight): pass >>> IncompKnight() TypeError: Can’t instantiate abstract class IncompKnight with abstract methods echo >>> AbstractKnight.__abstractmethods__ frozenset([’echo’]) class KnightImp(AbstractKnight): def echo(self): print ’Ni’ >>> KnightImp().echo() Ni
  • 37. abc em 2 minutos class AbstractKnight(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def echo(self): pass class IncompKnight(AbstractKnight): pass >>> IncompKnight() TypeError: Can’t instantiate abstract class IncompKnight with abstract methods echo >>> AbstractKnight.__abstractmethods__ frozenset([’echo’]) class KnightImp(AbstractKnight): def echo(self): print ’Ni’ >>> KnightImp().echo() Ni
  • 38. abc em 2 minutos class AbstractKnight(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def echo(self): pass class IncompKnight(AbstractKnight): pass >>> IncompKnight() TypeError: Can’t instantiate abstract class IncompKnight with abstract methods echo >>> AbstractKnight.__abstractmethods__ frozenset([’echo’]) class KnightImp(AbstractKnight): def echo(self): print ’Ni’ >>> KnightImp().echo() Ni
  • 39. Herdando dict class Dicto(dict): def __getitem__(self, k): return 31 >>> d = Dicto() >>> d[2] 31 >>> print d.get(2) None D’oh : (
  • 40. Herdando dict class Dicto(dict): def __getitem__(self, k): return 31 >>> d = Dicto() >>> d[2] 31 >>> print d.get(2) None D’oh : (
  • 41. Herdando dict class Dicto(dict): def __getitem__(self, k): return 31 >>> d = Dicto() >>> d[2] 31 >>> print d.get(2) None D’oh : (
  • 42. collections.abc • subclasses de builtin containers nem sempre produzem resultados esperados • subclasses de ABC produzem
  • 44. if you’re lazy Callable -> [’__call__’] Container -> [’__contains__’] Hashable -> [’__hash__’] ItemsView -> [] Iterable -> [’__iter__’] # ex: MutableMapping.__abstractmethods__ Iterator -> [’next’] for i in dir(collections): KeysView -> [] try: Mapping -> [’__iter__’, ’__getitem__’, ’__len__’] meths = list(getattr(collections, i MappingView -> [] ).__abstractmethods__) MutableMapping -> [’__delitem__’, ’__setitem__’, print i, ’->’, meths ’__getitem__’, ’__iter__’, ’__len__’] except: MutableSequence -> [’__delitem__’, ’__setitem__’, pass ’__getitem__’, ’__len__’, ’insert’] MutableSet -> [’discard’, ’add’, ’__iter__’, ’__len__’, ’__contains__’] Sequence -> [’__getitem__’, ’__len__’] Set -> [’__iter__’, ’__len__’, ’__contains__’] Sized -> [’__len__’] ValuesView -> []
  • 45. Subclassing dict de collections.MutableMapping from collections import MutableMapping class Dicto(MutableMapping): def __init__(self): self.d = {} >>> d = Dicto() >>> d[’eggs’] = ’ovos’ def __delitem__(self, i): >>> d[’ham’] = ’presunto’ del self.d[i] >>> for i in d: ... print i + ’:’ + d[i] def __setitem__(self, k, v): eggs:ovos self.d[k.lower()] = v ham:presunto >>> d.get(’HaM’) def __getitem__(self, k): presunto return self.d[k.lower()] >>> d[’eGGs’] ’ovos’ def __iter__(self): return iter(self.d) def __len__(self): return len(self.d)
  • 46. Subclassing dict de collections.MutableMapping from collections import MutableMapping class Dicto(MutableMapping): def __init__(self): self.d = {} >>> d = Dicto() >>> d[’eggs’] = ’ovos’ def __delitem__(self, i): >>> d[’ham’] = ’presunto’ del self.d[i] >>> for i in d: ... print i + ’:’ + d[i] def __setitem__(self, k, v): eggs:ovos self.d[k.lower()] = v ham:presunto >>> d.get(’HaM’) def __getitem__(self, k): presunto return self.d[k.lower()] >>> d[’eGGs’] ’ovos’ def __iter__(self): return iter(self.d) def __len__(self): return len(self.d)
  • 47. Referência • Lightning Talk de: no fisl 2011. • The Data Structures of Python, Alex Gaynor no PyCon2011 • http://www.doughellmann.com/PyMOTW/abc/index.html • http://docs.python.org/library/collections.html
  • 48. Dúvidas? André Ericson http://www.github.com/aericson de.ericson@gmail.com @_aericson