简体   繁体   English

在Python中的列表中乘法元素

[英]Multiplying Elements in a List in Python

Say I have a list 说我有一个清单

alist = [6, 6, 6, 3, 1]

And I want to multiply every element in the list by 4 and return 我想将列表中的每个元素乘以4并返回

alist = [24, 24, 24, 12, 4]

My current approach is to iterate through the list and multiply each element, just like: 我当前的方法是遍历列表并乘以每个元素,就像:

for i in range(len(alist)):
    alist[i] = alist[i] * 4

Which is very inefficient, because once the first 6*4 is calculated, it's redundant to calculate it again for the second and third sixes. 这是非常低效的,因为一旦计算出第一个6 * 4,就需要在第二个和第三个六个中再次计算它是多余的。 When I'm doing contest problems, it always exceeds the time limit once the numbers get large. 当我遇到比赛问题时,一旦数字变大,它总是超过时间限制。

Is there a way to do the same multiplication process that doesn't calculate the same thing over and over again? 有没有一种方法可以执行相同的乘法过程,而不会一次又一次地计算出相同的东西?

Interesting question, could this be what you are looking for: 有趣的问题,这可能是您要寻找的:

alist = [6,6,6,3,1]

adict = {a: a*4 for a in set(alist)}

alist = [adict[a] for a in alist]

You could use a memoized function, which means that it can look up old results. 您可以使用一个记忆功能,这意味着它可以查找旧结果。 For multiplication this might not help much, but for more complicated operations it can improve performance a lot. 对于乘法,这可能无济于事,但对于更复杂的运算,它可以大大提高性能。

cached_results = {}
def calc(a, b):
    if (a, b) not in cached_results:
        cached_results[(a, b)] = a*b
    else:
        print "already calculated value for (%s, %s)" % (a, b)
    return cached_results[(a, b)]

alist = [6, 6, 6, 3, 1]
print [calc(x, 4) for x in alist]

I am not sure if multiplication is what you would like to optimize here. 我不确定乘法是否是您要在此处优化的。 Instead, use list comprehension: 相反,请使用列表理解:

alist = [n * 4 for n in alist]

Or, use map 或者,使用map

alist = map(lambda n: n * 4, alist)

It is also recommended in Python Wiki on Performance Tips : 在性能提示的Python Wiki中也建议使用此方法:

List comprehensions were added to Python in version 2.0 as well. 列表推导也添加到了2.0版的Python中。 They provide a syntactically more compact and more efficient way of writing the above for loop. 它们提供了一种语法更紧凑,更高效的编写上述for循环的方式。

For longer lists a numpy array could be a better choice: 对于更长的列表,numpy数组可能是更好的选择:

anarray = numpy.array([6,6,6,3,1])
anarray *= 4

I am quite sure that any kind of lookup to make sure that you don't do the same multiplication twice takes longer than actually doing the multiplication once more. 我非常确定,要确保不会两次执行相同的乘法,任何查找都比再次进行乘法所需的时间更长。

您可以在列表理解中做到简单。

alist = [6,6,6,3,1] result = [x*4 for x in alist] print result

Good question use the inbuilt method append() in the python suppose in your case it is like Given list is like aList = [6, 6, 6, 3, 1] then use 很好的问题是在python中使用内置方法append() ,假设给定列表就像aList = [6,6,6,3,1]然后使用


b=List() b =列表()


for i in alist: 对于我在名单中:


    b.append(i*4)

print b #new list will take the result 打印b#新列表将获取结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM