将上一个元素添加到列表中的当前元素,然后分配给变量-Python 3.5.2
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了将上一个元素添加到列表中的当前元素,然后分配给变量-Python 3.5.2,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1736字,纯文字阅读大概需要3分钟。
内容图文
![将上一个元素添加到列表中的当前元素,然后分配给变量-Python 3.5.2](/upload/InfoBanner/zyjiaocheng/667/c1be7a1bcd7849ef87254063986d40bc.jpg)
关于此的第一篇文章,我很激动!好的,这是一个问题:如何将上一个元素添加到当前元素,然后从这些值中创建一个新列表,以将其添加到matplotlib图中?这是我的代码示例:
example_list = [20, 5, 5, -10]
print(example_list) '''first output should be'''
[20, 5, 5, -10]
value1 = (example_list[0])
value2 = (example_list[0] + example_list[1])
value3 = (example_list[0] + example_list[1] + example_list[2])
value4 = (example_list[0] + example_list[1] + example_list[2] + example_list[3])
”’我想你会明白我要提出的观点”’
删除example_list [:]
example_list.append(value1)
example_list.append(value2)
example_list.append(value3)
example_list.append(value4)
print(example_list)
'''output should be:'''
[20, 25, 30, 20]
”’这适用于对其进行硬编码,但是我希望这种情况适用于数百个元素. (当人们从我的“ simple_finance_app” Python脚本添加到列表时)”’谢谢您的帮助! (PS.我已经有了matplotlib代码,因此无需添加它,但是,它可以帮助阅读此问题/答案的其他人)
解决方法:
您可以使用itertools.accumulate方法:
from itertools import accumulate
from operator import add
result = list(accumulate(example_list,add))
这将产生:
>>> list(accumulate(example_list,add))
[20, 25, 30, 20]
如果函数(此处operator.add)在O(n)中起作用,则累加将在O(n)中起作用,而您的硬编码解决方案在O(n2)中起作用.
基本上,accumulate(iterable [,func])函数将一个可迭代的[x1,x2,…,xn]和一个函数f作为输入,并且每次迭代都在累加器和新元素上调用f.在第一步中,它发出第一个元素,然后累加器成为该元素.因此,它基本上会生成[x1,f(x1,x2),f(f(x1,x2),x3),…].但是没有每次都计算f(x1.x2).因此,它在语义上等效于:
def accumulate(iterable,func): # semantical equivalent of itertools.accumulate
iterer = iter(iterable)
try:
accum = next(iterer)
while True:
yield accum
accum = func(accum,next(iterer))
except StopIteration:
pass
但可能更不容易出错,而且效率更高.
内容总结
以上是互联网集市为您收集整理的将上一个元素添加到列表中的当前元素,然后分配给变量-Python 3.5.2全部内容,希望文章能够帮你解决将上一个元素添加到列表中的当前元素,然后分配给变量-Python 3.5.2所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。