使用 scipy.io.loadmat 将 .mat Matlab 文件中的字典键转换为 Python 中具有相同值的变量名

发布于 2024-11-15 11:30:28 字数 375 浏览 3 评论 0原文

我正在尝试使用 scipy.io.loadmat 从 .mat 文件加载基本字典 temp = {'key':array([1,2])} 。将 loadmat() 返回的 Python 字典文件中的键转换为变量名,其值与代表键相同。

例如:

temp = {'key':array([1,2])}

变成

key = array([1,2])

我知道如何用 temp.keys() 获取钥匙。然后抓取项目很容易,但如何强制 temp.keys() 中的字符串列表为变量名而不是字符串。

我希望这是有道理的,但这可能真的很容易,我只是不知道该怎么做。

干杯

I am trying to take a basic dictionary temp = {'key':array([1,2])} loaded from a .mat file with scipy.io.loadmat. Turn the keys in the Python dictionary file returned by loadmat() into variable names with values the same as the representing keys.

So for example:

temp = {'key':array([1,2])}

turned into

key = array([1,2])

I know how to grab the keys with temp.keys(). Then grabbing the items is easy but how do I force the list of strings in temp.keys() to be variable names instead of strings.

I hope this makes sense but this is probably really easy I just can't think how to do it.

Cheers

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

原谅过去的我 2024-11-22 11:30:28

在 python 中,方法参数可以使用 ** 魔法作为字典传递:

def my_func(key=None):
   print key
   #do the real stuff

temp = {'key':array([1,2])}

my_func(**temp)

>>> array([1,2])

In python, method parameters can be passed as dictionnaries with the ** magic:

def my_func(key=None):
   print key
   #do the real stuff

temp = {'key':array([1,2])}

my_func(**temp)

>>> array([1,2])
ゃ人海孤独症 2024-11-22 11:30:28

最好的办法是使用 temp['key']。但是,要回答这个问题,您可以使用 exec 函数。这样做的好处是,您不必硬编码任何变量名或将自己限制在函数内工作。

from numpy import array,matrix

temp = {'key':array([1,2]),'b': 4.3,'c': 'foo','d':matrix([2,2])}

for k in temp:
    exec('{KEY} = {VALUE}'.format(KEY = k, VALUE = repr(temp[k])))

>>> key
array([1, 2])
>>> b
4.3
>>> c
'foo'
>>> d
matrix([[2, 2]])

注意:仅当您从模块导入特定功能时,此操作才有效。如果由于代码实践或需要导入的函数数量过多而不想这样做,则可以编写一个函数来在条目前面连接模块名称。输出与前面的示例相同。

import numpy as np,numpy

temp = {'key':np.array([1,2]),'b': 4.3,'c': 'foo','d':np.matrix([2,2])}

def exec_str(key,mydict):
    s = str(type(mydict[key]))
    if '.' in s:
        start = s.index("'") + 1
        end = s.index(".") + 1
        v = s[start:end:] + repr(mydict[key])
    else:
        v = repr(mydict[key])     
    return v

for k in temp:
    exec('{KEY} = {VALUE}'.format(KEY = k, VALUE = exec_str(k,temp)))

虽然这不是最佳的代码实践,但它对于我测试的所有示例都很有效。

The best thing to do is to use temp['key']. To answer the question, however, you could use the exec function. The benefits of doing it this way is that you can do this don't have to hard code any variable names or confine yourself to work inside a function.

from numpy import array,matrix

temp = {'key':array([1,2]),'b': 4.3,'c': 'foo','d':matrix([2,2])}

for k in temp:
    exec('{KEY} = {VALUE}'.format(KEY = k, VALUE = repr(temp[k])))

>>> key
array([1, 2])
>>> b
4.3
>>> c
'foo'
>>> d
matrix([[2, 2]])

NOTE : This will only work if you have imported the specific function from the modules. If you don't want to do this because of code practice or the sheer volume of function that you would need to import, you could write a function to concatenate the module name in front of the entry. Output is the same as the previous example.

import numpy as np,numpy

temp = {'key':np.array([1,2]),'b': 4.3,'c': 'foo','d':np.matrix([2,2])}

def exec_str(key,mydict):
    s = str(type(mydict[key]))
    if '.' in s:
        start = s.index("'") + 1
        end = s.index(".") + 1
        v = s[start:end:] + repr(mydict[key])
    else:
        v = repr(mydict[key])     
    return v

for k in temp:
    exec('{KEY} = {VALUE}'.format(KEY = k, VALUE = exec_str(k,temp)))

While this isn't the best code practice, It works well for all of the examples I tested.

葬花如无物 2024-11-22 11:30:28

更好的方法可能是将数据填充到一个单独的对象中:

class attrdict(dict):
    def __getattr__(self, k): return self[k]
    def __setattr__(self, k, v): self[k] = v

somedict = {'key': 123, 'stuff': 456}

data = attrdict(somedict)
print data.key
print data.stuff

这很容易交互使用,并且不需要任何魔法。
这对于 Matlab 用户来说也应该没问题。

编辑:事实证明,下面的内容在大多数情况下实际上不起作用。太糟糕了,魔法就这么多了。

不过,如果您想使用魔法,您可以执行类似这样的操作,

locals().update(somedict)

这将可以交互地正常工作,您甚至可以通过弄乱 sys 来隐藏对加载器函数内的 locals() 的访问._getframe().f_back.f_locals

然而,这在函数中不起作用:

def foo():
    locals().update({'a': 4})
    print a 

重点是上面的 a 在编译时绑定到全局变量,因此 Python 不会尝试在局部变量中查找它。

A better way may be to stuff the data to a separate object:

class attrdict(dict):
    def __getattr__(self, k): return self[k]
    def __setattr__(self, k, v): self[k] = v

somedict = {'key': 123, 'stuff': 456}

data = attrdict(somedict)
print data.key
print data.stuff

This is about as easy to use interactively, and does not require any magic.
This should be OK for Matlab-users, too.

EDIT: turns out the stuff below doesn't actually work most of the time. Too bad, so much for magic.

If you want to meddle with magic, though, you can do something like

locals().update(somedict)

This will work fine interactively, and you can even hide the access to locals() inside the loader function by messing with sys._getframe().f_back.f_locals.

However, this will not work in functions:

def foo():
    locals().update({'a': 4})
    print a 

The point is that a above is bound to global variable at compile time, and so Python does not try looking it up in among local variables.

黒涩兲箜 2024-11-22 11:30:28

正如 hdhagman 回答的那样,使用 exec() 更简单。我写了更简单的代码。

temp = {'key':[1,2]}

for k, v in temp.items():
    exec("%s = %s" % (k, v))

print(key)
=> [1,2]

To use exec() is more simple as hdhagman answered. I write more simple code.

temp = {'key':[1,2]}

for k, v in temp.items():
    exec("%s = %s" % (k, v))

print(key)
=> [1,2]

捶死心动 2024-11-22 11:30:28

对于 numpy 数组和其他非内置类型,上面的答案都不适合我。但是,执行了以下操作:

import numpy as np
temp = {'a':np.array([1,2]), 'b': 4.3, 'c': 'foo', 'd':np.matrix([2,2])}
for var in temp.keys():
    exec("{} = temp['{}']".format(var, var))

注意引号的顺序。这使得 var 在第一个实例中被视为变量,然后在第二个实例中被视为键,索引到 temp 字典中。

当然,关于 exec() 和 eval() 危险的常见免责声明仍然适用,并且您应该仅在您绝对信任的输入上运行此命令。

None of the answers above worked for me with numpy arrays and other non-built-in types. However, the following did:

import numpy as np
temp = {'a':np.array([1,2]), 'b': 4.3, 'c': 'foo', 'd':np.matrix([2,2])}
for var in temp.keys():
    exec("{} = temp['{}']".format(var, var))

Note the order of the quotes. This allows var to be treated as a variable in the first instance, and then as a key in the second instance, indexing into the temp dictionary.

Of course, the usual disclaimers about the dangers of exec() and eval() still apply, and you should only run this on input you absolutely trust.

蹲墙角沉默 2024-11-22 11:30:28

虽然我建议直接使用字典并访问诸如 temp['key'] 之类的数组,但如果您提前知道所有变量名称,您可以编写一个函数将它们提取到各个变量:

def func(**kwargs):
    return kwargs['a'],kwargs['b']


temp = {'a':np.array([1,2]),'b':np.array([3,4])}
a,b = func(**temp)
del temp # get rid of temporary dict

While I would just recommend using the dictionary directly and accessing the arrays like temp['key'], if you knew all of the variable names ahead of time you could write a function to extract them to individual variables:

def func(**kwargs):
    return kwargs['a'],kwargs['b']


temp = {'a':np.array([1,2]),'b':np.array([3,4])}
a,b = func(**temp)
del temp # get rid of temporary dict
一张白纸 2024-11-22 11:30:28

我有同样的问题,我根据其他人的答案尝试了这个代码。在这里,我使用 pickle 而不是 Matlab 来存储和检索数据。

保存数据

x1=[2,4,6,8,10]
x2=[1,3,5,7,9]
x3='hello world'
vars={'x1':'x1','x2':'x2','x3':'x3'}

file='test.pickle'
f = open(file,'wb')
for key in vars.keys():
    pickle.dump(eval(vars[key]),f)

del x1,x2,x3

从文件中读取

s = open(file,'rb')
for k in vars:
    exec('{KEY} = {VALUE}'.format(KEY = k, VALUE = repr(pickle.load(s))))

print(x1,x2,x3)

I had the same question and I tried this code based on the other's answers. Here I used pickle instead of Matlab to store and retrieve the data.

To save data

x1=[2,4,6,8,10]
x2=[1,3,5,7,9]
x3='hello world'
vars={'x1':'x1','x2':'x2','x3':'x3'}

file='test.pickle'
f = open(file,'wb')
for key in vars.keys():
    pickle.dump(eval(vars[key]),f)

del x1,x2,x3

to read from the file

s = open(file,'rb')
for k in vars:
    exec('{KEY} = {VALUE}'.format(KEY = k, VALUE = repr(pickle.load(s))))

print(x1,x2,x3)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文