小编mgi*_*son的帖子

将二进制字符串转换为numpy数组

假设我有字符串:

my_data = '\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@'
Run Code Online (Sandbox Code Playgroud)

我得到它是无关紧要的,但为了具体的东西,假设我从二进制文件中读取它.

我知道我的字符串是4(4字节)浮点数的二进制表示.我想把这些花车作为一个numpy阵列.我做到:

import struct
import numpy as np
tple = struct.unpack( '4f', my_data )
my_array = np.array( tple, dtype=np.float32 )
Run Code Online (Sandbox Code Playgroud)

但是创建一个中间元组似乎很愚蠢.有没有办法在不创建中间元组的情况下执行此操作?

编辑

我还希望能够以这样的方式构造数组,以便我可以指定字符串的字节顺序.

python numpy binary-data

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

Python:避免__getattribute__中的无限循环

__getattribute__需要仔细编写该方法以避免无限循环.例如:

class A:
    def __init__(self):
        self.x = 100

    def __getattribute__(self, x):
        return self.x

>>> a = A()
>>> a.x    # infinite looop
RuntimeError: maximum recursion depth exceeded while calling a Python object


class B:
    def __init__(self):
        self.x = 100

    def __getattribute__(self, x):
        return self.__dict__[x]

>>> b = B()
>>> b.x    # infinite looop
RuntimeError: maximum recursion depth exceeded while calling a Python object
Run Code Online (Sandbox Code Playgroud)

因此我们需要以这种方式编写方法:

class C:
    def __init__(self):
        self.x = 100

    def __getattribute__(self, x):
        # 1. error
        # AttributeError: …
Run Code Online (Sandbox Code Playgroud)

python python-3.x

25
推荐指数
3
解决办法
9945
查看次数

Python替换函数[替换一次]

我需要帮助我用Python编写的程序.

假设我想每一个字的情况下更换"steak""ghost"(只是用它去......),但我也希望每一个字的情况下更换"ghost""steak"在同一时间.以下代码不起作用:

 s="The scary ghost ordered an expensive steak"
 print s
 s=s.replace("steak","ghost")
 s=s.replace("ghost","steak")
 print s
Run Code Online (Sandbox Code Playgroud)

它打印: The scary steak ordered an expensive steak

我想要得到的是 The scary steak ordered an expensive ghost

python string replace

22
推荐指数
3
解决办法
3079
查看次数

如何使用Python删除文本文件的第一行?

我一直在网上搜索,但没有找到任何好的解决方案.

这是我的文本文件:

[54, 95, 45, -97, -51, 84, 0, 32, -55, 14, 50, 54, 68, -3, 57, 88, -1]
[24, 28, 38, 37, 9, 44, -14, 84, -40, -92, 86, 94, 95, -62, 12, -36, -12]
[-26, -67, -89, -7, 12, -20, 76, 88, -15, 38, -89, -65, -53, -84, 31, -81, -91]
[-19, -50, 16, 47, -42, -31, 75, 0, 25, -95, 75, 97, 19, 77, -2, -31, -59]
[-66, -10, 35, -39, 24, 70, 74, -45, -27, 77, …
Run Code Online (Sandbox Code Playgroud)

python file

22
推荐指数
5
解决办法
7万
查看次数

为什么切片分配比`list.insert`更快?

受到这个好答案的启发,

这是一个基准:

import timeit

def test1():
    a = [1,2,3]
    a.insert(0,1)

def test2():
    a = [1,2,3]
    a[0:0]=[1]

print (timeit.timeit('test1()','from __main__ import test1'))
print (timeit.timeit('test2()','from __main__ import test2'))
Run Code Online (Sandbox Code Playgroud)

对我来说,test2速度更快(~10%).为什么会这样?我希望它会变慢:

  1. 切片赋值必须能够接受任何长度的迭代,因此必须更通用.
  2. 在切片分配中,我们需要在右侧创建一个新列表才能使其工作.

任何人都可以帮我理解这个吗?

(在OS-X 10.5.8上使用python 2.7)

python optimization performance python-internals

20
推荐指数
1
解决办法
807
查看次数

组织git分支

我正在开发一个使用git作为VCS的大型项目.在任何给定的时间我正在努力实现一些功能/错误修正等.对于任何给定的功能/错误,创建分支的层次结构将是很好的 - 例如

$ git branch
  feature1
       sub-branch1
       sub-branch2
       sub-branch3
  feature2
       sub-brancha
      *sub-branchb  #<--currently checked out
       sub-branchc
  bugfix1
       sub-branch-foo

$ git checkout sub-brancha
$ git branch
  feature1
       sub-branch1
       sub-branch2
       sub-branch3
  feature2
      *sub-brancha  #<--currently checked out
       sub-branchb  
       sub-branchc
  bugfix1
       sub-branch-foo
Run Code Online (Sandbox Code Playgroud)

有可能做这样的事情,还是我需要采用更原始的命名方案?

编辑

为了使它稍微具体是什么我要找的,如果特征1是一个Git分支,然后在上面的例子中,子BRANCH1将所有已创建git checkout -b sub-branch1feature1分支(这是从主支).例如:

$ git checkout master
$ git checkout -b feature1
$ git checkout -b testing
$ git branch
master
   feature1
     *testing
$ git checkout master
$ git checkout -b feature2
$ git …
Run Code Online (Sandbox Code Playgroud)

git branch

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

如何在python中获取调用者的文件名,方法名称

例如,a.boo方法调用b.foo方法.在b.foo方法中,我如何获取文件名(我不想传递__file__b.foo方法)...

python

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

设置matplotlib颜色条范围

我想设置matplotlib颜色条范围.这是我到目前为止所拥有的:

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(20)
y = np.arange(20)
data = x[:-1,None]+y[None,:-1]

fig = plt.gcf()
ax = fig.add_subplot(111)

X,Y = np.meshgrid(x,y)
quadmesh = ax.pcolormesh(X,Y,data)
plt.colorbar(quadmesh)

#RuntimeError: You must first define an image, eg with imshow
#plt.clim(vmin=0,vmax=15)  

#AttributeError: 'AxesSubplot' object has no attribute 'clim'
#ax.clim(vmin=0,vmax=15) 

#AttributeError: 'AxesSubplot' object has no attribute 'set_clim'
#ax.set_clim(vmin=0,vmax=15) 

plt.show()
Run Code Online (Sandbox Code Playgroud)

如何在此处设置颜色条限制?

python matplotlib

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

python运算符,没有"不在"的运算符

这可能是一个愚蠢的问题,但是看看运算符到函数的映射,我注意到没有表达not in运算符的函数.起初我认为这可能是因为解释器只是重新排序not x in y,但有一个函数is not似乎应该表现得完全相同not in.我错过了什么,或者该操作员真的不存在?

这是一个非常愚蠢的例子,你可能想要这个:

def compare_iter(a,b,func):
    return [func(aa,bb) for aa,bb in zip(a,b)]

my_compare=compare_iter(xx,yy,lambda x,y:x not in y)  #lambda -- yuck
my_compare=map(operator.not_,compare_iter(xx,yy,operator.contains)  #extra map?  grr...
#it would be nice to do: my_compare=compare_iter(xx,yy,operator.not_contains)
Run Code Online (Sandbox Code Playgroud)

当然我可以为此编写自己的函数,但是你需要为效率付出代价,而运算符模块可以将这些代码从python中推出,因此执行速度更快.

python indexing performance

18
推荐指数
1
解决办法
5980
查看次数

Python - Ceil将日期时间提升到下一刻钟

让我们想象一下这个日期时间

>>> import datetime
>>> dt = datetime.datetime(2012, 10, 25, 17, 32, 16)
Run Code Online (Sandbox Code Playgroud)

我想把它提交给下一个四分之一小时,以便获得

datetime.datetime(2012, 10, 25, 17, 45)
Run Code Online (Sandbox Code Playgroud)

我想象的东西

>>> quarter = datetime.timedelta(minutes=15)
>>> import math
>>> ceiled_dt = math.ceil(dt / quarter) * quarter
Run Code Online (Sandbox Code Playgroud)

但当然这不起作用

python math datetime ceil

18
推荐指数
3
解决办法
9148
查看次数