如何在python中的列表元素上进行数学运算? [英] how can i do math operation on list elements in python?

查看:2046
本文介绍了如何在python中的列表元素上进行数学运算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有数字列表[3, 51, 34].我想向每个元素添加先前元素的总和,并使用这些新值返回一个新列表. 因此,这里的结果将是[3, 54, 88].通常如何在任意大小的输入列表上执行此操作?该代码的最后一行应适用于已知的尺寸列表.

Suppose i have list of numbers [3, 51, 34]. I want to add to each element the sum of the previous elements and return a new list with these new values. So here the result would be [3, 54, 88]. How to do it in general on an arbitrary-sized input list? The last line of this code should work on the known size lists.

indices1 = range(len(list1))

indices1.sort(key=lambda x: list2[x])
list1 = map(lambda i: list1[i], indices1)
labelled = zip(list1, ascii_uppercase)
sorted_data = sorted(labelled, key=itemgetter(0)) 

labels = [pair[1] for pair in sorted_data]
newlist, = [ 0, list1[0], list1[1] + list1[2], list1[0] + list[1] + list[2]]

推荐答案

一个简单的减少:

nums = [3,51,34]
reduce(lambda x, y: [y] if not x else x + [y + x[-1]], nums, None)
# [3, 54, 88]

这篇关于如何在python中的列表元素上进行数学运算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆