Multiplying a tuple by a scalar

后端 未结 12 879
忘了有多久
忘了有多久 2020-12-14 14:48

I have the following code:

print(img.size)
print(10 * img.size)

This will print:

(70, 70)
(70, 70, 70, 70, 70, 70, 70, 70,          


        
相关标签:
12条回答
  • 2020-12-14 14:53

    adding nothing but variety..

    import operator
    img_size = (70, 70)
    map(operator.mul, img_size, len(img_size)*(10,))
    
    0 讨论(0)
  • 2020-12-14 14:54

    If you have this problem more often and with larger tuples or lists then you might want to use the numpy library, which allows you to do all kinds of mathematical operations on arrays. However, in this simple situation this would be complete overkill.

    0 讨论(0)
  • 2020-12-14 14:57

    You can try something like this:

    print [10 * s for s in img.size]
    

    It will give you a new list with all the elements you have in the tuple multiplied by 10

    0 讨论(0)
  • 2020-12-14 15:00

    In line with the previous answers but using numpy:

    import numpy as np
    result = tuple(10*np.array(img.size))
    
    0 讨论(0)
  • 2020-12-14 15:02

    Just to overview

    import timeit
    
    # tuple element wise operations multiplication
    
    # native
    map_lambda = """
    a = tuple(range(10000))
    b = tuple(map(lambda x: x * 2, a))
    """
    
    # native
    tuple_comprehension = """
    a = tuple(range(10000))
    b = tuple(x * 2 for x in a)
    """
    
    # numpy
    using_numpy = """
    import numpy as np
    a = tuple(range(10000))
    b = tuple((np.array(a) * 2).tolist())
    """
    
    print('map_lambda =', timeit.timeit(map_lambda, number=1000))
    print('tuple_comprehension =', timeit.timeit(tuple_comprehension, number=1000))
    print('using_numpy =', timeit.timeit(using_numpy, number=1000))
    

    Timings on my machine

    map_lambda = 1.541315148000649
    tuple_comprehension = 1.0838452139996662
    using_numpy = 1.2488984129995515
    
    0 讨论(0)
  • 2020-12-14 15:05

    The pythonic way would be using a list comprehension:

    y = tuple([z * 10 for z in img.size])
    

    Another way could be:

    y = tuple(map((10).__mul__, img.size))
    
    0 讨论(0)
提交回复
热议问题