How to multiply all integers inside list [duplicat

2019-01-06 18:24发布

This question already has an answer here:

Hello so I want to multiply the integers inside a list.

For example;

l = [1, 2, 3]
l = [1*2, 2*2, 3*2]

output:

l = [2, 4, 6]

So I was searching online and most of the answers were regarding multiply all the integers with each other such as:

[1*2*3]

6条回答
趁早两清
2楼-- · 2019-01-06 19:07

The most pythonic way would be to use a list comprehension:

l = [2*x for x in l]

If you need to do this for a large number of integers, use numpy arrays:

l = numpy.array(l, dtype=int)*2

A final alternative is to use map

l = list(map(lambda x:2*x, l))
查看更多
再贱就再见
3楼-- · 2019-01-06 19:13
#multiplying each element in the list and adding it into an empty list
original = [1, 2, 3]
results = []
for num in original:
    results.append(num*2)# multiply each iterative number by 2 and add it to the empty list.

print(results)
查看更多
爷、活的狠高调
4楼-- · 2019-01-06 19:18

Another functional approach which is maybe a little easier to look at than an anonymous function if you go that route is using functools.partial to utilize the two-parameter operator.mul with a fixed multiple

>>> from functools import partial
>>> from operator import mul
>>> double = partial(mul, 2)
>>> list(map(double, [1, 2, 3]))
[2, 4, 6]
查看更多
神经病院院长
5楼-- · 2019-01-06 19:19

using numpy :

    In [1]: import numpy as np

    In [2]: nums = np.array([1,2,3])*2

    In [3]: nums.tolist()
    Out[4]: [2, 4, 6]
查看更多
The star\"
6楼-- · 2019-01-06 19:23

The simplest way to me is:

map((2).__mul__, [1, 2, 3])
查看更多
等我变得足够好
7楼-- · 2019-01-06 19:28

Try a list comprehension:

l = [x * 2 for x in l]

This goes through l, multiplying each element by two.

Of course, there's more than one way to do it. If you're into lambda functions and map, you can even do

l = map(lambda x: x * 2, l)

to apply the function lambda x: x * 2 to each element in l. This is equivalent to:

def timesTwo(x):
    return x * 2

l = map(timesTwo, l)
查看更多
登录 后发表回答