Python列表元素明智的条件增量 [英] python list element wise conditional increment

查看:81
本文介绍了Python列表元素明智的条件增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了一段时间,基本上我正在尝试有条件地将一个元素的列表有条件地增加另一个元素的列表...

I have been searching this for a while, basically I am trying to conditionally increment a list of element by another list, element-wise...

我的代码正在执行,但是有更好的方法吗?列表理解,地图?

my code is following, but is there a better way to do it? list comprehension, map??

我认为 http://www中的〜+ =这样的元素运算符.python.org/dev/peps/pep-0225/真的很好,但是为什么要推迟呢?

I think a element-wise operator like ~+= from http://www.python.org/dev/peps/pep-0225/ would be really good, but why is it deferred?

for i in range(1,len(s)):
        if s[i]<s[0]:
            s[i]+=p[i]

基于你们的一些良好反馈,我已将其重新编码为以下内容

based on some good feedbacks from you guys I have recoded to the following

i=s<s[0]
s[i]+=p[i]

和s,p都是数组.

p.s仍然比我的代码之一慢5倍.

p.s still slow than matlab 5 times for one of my code.

推荐答案

如果您不想创建新的数组,则可以选择:

If you don't want to create a new array, then your options are:

  1. 您提出的建议(尽管您可能希望使用xrange取决于python版本)
  2. 对s和p使用Numpy数组.如果s和p的长度相同,则可以执行s[s<s[0]] += p[s<s[0]]之类的操作.
  3. 使用Cython加快您的建议.
  1. What you proposed (though you might want to use xrange depending on the python version)
  2. Use Numpy arrays for s and p. Then you can do something like s[s<s[0]] += p[s<s[0]] if s and p are the same length.
  3. Use Cython to speed up what you've proposed.

这篇关于Python列表元素明智的条件增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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