There is a zip and enumerate function. How can the code be simplified?



  • def zi(*iterables):
        length = min(map(len, iterables))
        result = []
        for index in range(length):
            new_item = tuple(map(lambda item: item[index], iterables))
            result.append(new_item)
        return result
    
    def enumerat(iterable, start=0):
        result = []
        for index in range(len(iterable)):
            new_item = (index + start, iterable[index])
            result.append(new_item)
        return result
    


  • The key question is "HOW":

    But you can ask for the code:

    def zi(*iterables):
        return [tuple(map(lambda item: item[index], iterables)) for index in range(min(map(len, iterables)))]
    

    and

    def enumerat(iterable, start=0):
        return [(index + start, iterable[index]) for index in range(len(iterable))]
    

    P. S.

    using a function zip could be reduced. enumerat:

    def enumerat(iterable, start=0):
        return zip(range(start, start + len(iterable)), iterable)
    

Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2