小编mgi*_*son的帖子

python中的前缀匹配

我有一个字符串:

" This is such an nice artwork"
Run Code Online (Sandbox Code Playgroud)

我有一个tag_list ["art","paint"]

基本上,我想写一个函数,接受这个字符串和taglist作为输入,并返回单词"artwork",因为艺术作品包含在taglist中的单词art.

我如何最有效地做到这一点?

我希望这在速度方面是有效的

 def prefix_match(string, taglist):
        # do something here
     return word_in string
Run Code Online (Sandbox Code Playgroud)

python

6
推荐指数
1
解决办法
1万
查看次数

按字符串调用方法

我有以下课程.

func_list= ["function1", "function2", "function3"]

class doit(object):
    def __init__(self):
        for item in func_list:
            if item == "function1":
                self.function1()
            elif item == "function2":
                self.function2()
            elif item == "function3":
                self.function3()

    def function1(self):
        #do this
        pass
    def function2(self):
        #do that
        pass
    def function3(self):
        pass
Run Code Online (Sandbox Code Playgroud)

如果创建了此类的实例,它将遍历字符串列表并根据实际字符串调用方法.列表中的字符串具有相应方法的名称.

我怎样才能以更优雅的方式做到这一点?我不想为elif我添加到列表中的每个"函数" 添加另一个路径.

python python-2.5

6
推荐指数
1
解决办法
2679
查看次数

Python如何迭代for循环?

我在Python上尝试了以下代码,这就是我所得到的:似乎我尝试通过更改elem来对迭代进行许多更改,但它不起作用.

lis = [1,2,3,4,5]
for elem in lis:
    elem = 3

print lis
[1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)

但是,如果迭代物是具有自己的方法(如列表)的对象,则可以在for循环中修改它们.

lis = [[1],[2]]
for elem in lis:
    elem.append(8)

print lis
    [[1, 8], [2, 8]]
Run Code Online (Sandbox Code Playgroud)

for循环中究竟什么是"elem"术语?提前致谢!

python loops for-loop

6
推荐指数
2
解决办法
255
查看次数

为什么重写__contains__会破坏OrderedDict.keys?

我正在继承OrderedDict(Cpython,2.7.3)来表示数据文件. __getitem__从数据文件中提取一个字段并将其设置在当前实例上,类似于我在下面发布的代码.现在我想覆盖__contains__返回,True如果字段在字典中或磁盘上的文件中,因为它可以以任何方式读取.然而,这似乎打破OrderedDict了检查它的钥匙的能力.

from collections import OrderedDict

dictclass = OrderedDict

class Foo(dictclass):
    def __getitem__(self,key):
        try:
            return dictclass.__getitem__(self,key)
        except KeyError:
            pass

        data = key*2
        self[key] = data
        return data

    def __contains__(self,whatever):
        return dictclass.__contains__(self,whatever) or 'bar' in whatever

a = Foo()
print a['bar']
print a.keys()
Run Code Online (Sandbox Code Playgroud)

如果您运行上面的代码,您将获得此输出:

barbar
[]
Run Code Online (Sandbox Code Playgroud)

请注意,如果您更改dictclass = dict上面的代码,它似乎仍然有效(给出以下输出).

barbar
['bar']
Run Code Online (Sandbox Code Playgroud)

我做错了什么吗?

python python-2.7

6
推荐指数
1
解决办法
350
查看次数

numpy插入轴使数据不连续

为什么插入新轴会使数据不连续?

>>> a = np.arange(12).reshape(3,4,order='F')
>>> a
array([[ 0,  3,  6,  9],
       [ 1,  4,  7, 10],
       [ 2,  5,  8, 11]])
>>> a.reshape((3,1,4)).flags
  C_CONTIGUOUS : False
  F_CONTIGUOUS : False
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  UPDATEIFCOPY : False
>>> a[np.newaxis,...].flags
  C_CONTIGUOUS : False
  F_CONTIGUOUS : False
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  UPDATEIFCOPY : False
>>> a.flags
  C_CONTIGUOUS : False
  F_CONTIGUOUS : True
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  UPDATEIFCOPY …
Run Code Online (Sandbox Code Playgroud)

python numpy

6
推荐指数
1
解决办法
334
查看次数

将掩码数组添加到另一个fortran的最有效方法

我有一个"蒙面数组",我想添加到另一个数组 - 换句话说,我有3个数组A,Bmask.我的问题是什么是最有效的(在执行时间方面)存储掩码的方式(作为逻辑数组,作为1和0的真实数组)?

编辑

这是一个你可以玩的玩具程序(如果你有mpif77):

  program main
  implicit None
  include 'mpif.h'
  integer, parameter :: ntry=10000
  integer, parameter :: asize=1000000
  real,dimension(asize) :: A,B,maskr
  logical,dimension(asize) :: mask
  real*8 :: dd,dt,dtave,dtbest
  integer i

  do i=1,asize
     maskr(i)=mod(i,2)
     mask(i)=.False.
     if(mod(i,2).eq.0) mask(i)=.True.
  enddo

  A=1.0; B=1.0
  dtbest=1d33
  dtave=0.0
  do i=1,ntry
     dt=mpi_wtime()
     call add_arrays_logical(asize,A,B,mask)
     dt=mpi_wtime()-dt
     dtbest=min(dt,dtbest)
     dtave=dtave+dt
  enddo
  print*,"==== logical ==="
  print*,"Average",dtave/ntry
  print*,"Best",dtbest

  A=1.0; B=1.0
  dtbest=1d33
  dtave=0.0
  do i=1,ntry
     dt=mpi_wtime()
     call add_arrays_real(asize,A,B,maskr)
     dt=mpi_wtime()-dt
     dtbest=min(dt,dtbest)
     dtave=dtave+dt
  enddo
  print*,"==== Real ==="
  print*,"Average",dtave/ntry
  print*,"Best",dtbest

  A=1.0; …
Run Code Online (Sandbox Code Playgroud)

performance fortran

5
推荐指数
2
解决办法
1986
查看次数

试图将收益率理解为一种表达方式

我正在玩生成器和生成器表达式,我不完全确定我理解它们是如何工作的(一些参考资料):

>>> a = (x for x in range(10))
>>> next(a)
0
>>> next(a)
1
>>> a.send(-1)
2
>>> next(a)
3
Run Code Online (Sandbox Code Playgroud)

所以看起来好像generator.send被忽略了.这是有道理的(我猜)因为没有明确的yield表达式来捕获发送的信息......

然而,

>>> a = ((yield x) for x in range(10))
>>> next(a)
0
>>> print next(a)
None
>>> print next(a)
1
>>> print next(a)
None
>>> a.send(-1)  #this send is ignored, Why? ... there's a yield to catch it...
2
>>> print next(a)
None
>>> print next(a)
3
>>> a.send(-1)  #this send …
Run Code Online (Sandbox Code Playgroud)

python generator

5
推荐指数
0
解决办法
417
查看次数

在 gnuplot 中拟合分段函数

我想在 gnuplot 中拟合多个有界函数,同时拟合边界值。

例如:

f(x)=a          (for x < b)

f(x)=a+(x-b)**c (for x > b)

fit f(x) 'data.dat' via a,b,c
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?

gnuplot function curve-fitting bounds fitbounds

5
推荐指数
1
解决办法
1360
查看次数

使用ConfigParser多次指定相同的选项

我想使用python ConfigParser模块读取配置文件:

[asection]
option_a = first_value
option_a = second_value
Run Code Online (Sandbox Code Playgroud)

我希望能够获得为选项“ option_a”指定的值的列表。我尝试了以下显而易见的方法:

test = """[asection]
option_a = first_value
option_a = second_value
"""
import ConfigParser, StringIO
f = StringIO.StringIO(test)
parser = ConfigParser.ConfigParser()
parser.readfp(f)
print parser.items()
Run Code Online (Sandbox Code Playgroud)

哪个输出:

[('option_a', 'second_value')]
Run Code Online (Sandbox Code Playgroud)

当我希望:

[('option_a', 'first_value'), ('option_a', 'second_value')]
Run Code Online (Sandbox Code Playgroud)

或者,甚至更好:

[('option_a', ['first_value', 'second_value'])]
Run Code Online (Sandbox Code Playgroud)

有没有办法用ConfigParser做到这一点?另一个主意?

python configparser

5
推荐指数
1
解决办法
1064
查看次数

numpy distutils - 如果你失败了,尝试编译一些东西并设置标志

在*NIX平台上构建源代码的一种常用方法是使用configure脚本.在引擎盖下,configure尝试构建一堆测试程序,以确定您可以访问哪些库.然后它生成一个头文件,它包含在项目中,有条件地定义了一堆宏,以便程序员可以提供替代或构建库/程序的精简版本,如果缺少特定的"依赖".有什么功能相同的使用numpy.distutils吗?

举个例子,这是我的setup.py:

from numpy.distutils.misc_util import Configuration

def configuration(parent_package='',top_path=None):
    config = Configuration('pyggcm',parent_package,top_path)

    #TODO: Currently, I have some macros to conditionally build the seek-code
    #Unfortunately, that's not the best solution (by far).  Perhaps if we
    #changed to using stream access it would work better, without the need
    #for these silly macros.
    config.add_extension('_fortfile',sources=['_fortfile/_fortfile.F90'],
                         define_macros=[
                             ('FSEEKABLE',1),  #compiler provides fseek and ftell
                             ('HAVE_STREAM',1) #compiler provides access='stream' for opening files. (f2003 standard)
                             ])  

    config.add_extension('jrrle',sources=['jrrle/jrrle.f90'])
    config.add_scripts(['scripts/ggcm_timehist',
                        'scripts/ggcm_plasmasheet',
                        'scripts/ggcm_plot'])
    return config


from …
Run Code Online (Sandbox Code Playgroud)

python distutils numpy

5
推荐指数
1
解决办法
382
查看次数