multiply utple or list

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Jim Red

    multiply utple or list

    what is the best way to multiply a tuple or list by a given value

    exp.
    multiply (4, 5) by 2 => (8, 10)

    cheers

    jr
  • Karl Scalet

    #2
    Re: multiply utple or list

    Jim Red wrote:[color=blue]
    > what is the best way to multiply a tuple or list by a given value
    >
    > exp.
    > multiply (4, 5) by 2 => (8, 10)
    >
    > cheers
    >
    > jr[/color]

    i.e.:
    [color=blue][color=green][color=darkred]
    >>> import operator
    >>> [ operator.mul(x, 2) for x in (4,5)][/color][/color][/color]

    regards,
    Karl

    Comment

    • P@draigBrady.com

      #3
      Re: multiply utple or list

      Jim Red wrote:[color=blue]
      > what is the best way to multiply a tuple or list by a given value
      >
      > exp.
      > multiply (4, 5) by 2 => (8, 10)[/color]

      something like this?

      import types
      def multiply_sequen ce(sequence, multiplier):
      new_sequence = map(lambda item: item*multiplier , sequence)
      if type(sequence) == types.TupleType :
      return tuple(new_seque nce)
      elif type(sequence) == types.ListType:
      return new_sequence

      --
      Pádraig Brady - http://www.pixelbeat.org

      Comment

      • Diez B. Roggisch

        #4
        Re: multiply utple or list

        > >>> import operator[color=blue][color=green][color=darkred]
        > >>> [ operator.mul(x, 2) for x in (4,5)][/color][/color][/color]

        Why not simply * ?

        [ x * 2 for x in (4,5)]

        And you might surround it by tuple to gain a tuple

        tuple([ x * 2 for x in (4,5)])

        Another way would be to use Numeric

        import Numeric
        a = Numeric.array(( 10,2), Numeric.Float32 )
        a = a * 2


        --
        Regards,

        Diez B. Roggisch

        Comment

        • Karl Scalet

          #5
          Re: multiply utple or list

          Diez B. Roggisch wrote:
          [color=blue][color=green][color=darkred]
          >> >>> import operator
          >> >>> [ operator.mul(x, 2) for x in (4,5)][/color][/color]
          >
          >
          > Why not simply * ?
          >
          > [ x * 2 for x in (4,5)]
          >[/color]

          oops, of course. I had the map function in mind,
          which only accepts a function, but this would come
          to something like:

          li=(4,5)
          map(operator.mu l, li, (2,)*len(li))

          and is certainly worse then list comprehension :-)

          regards,
          Karl

          Comment

          Working...