在numpy数组上实现ast.literal_eval [英] Implementing ast.literal_eval on a numpy array

查看:273
本文介绍了在numpy数组上实现ast.literal_eval的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下表达式,您可以将字符串转换为python dict。

 >>> import ast 
>>>> a = ast.literal_eval({'muffin':'lolz','foo':'kitty'})
>>> a
{'松饼':'lolz','foo':'kitty'}

使用以下表达式,您可以获得foo值:

 >>> a.get('foo')

我有一个类似于python dict格式的字符串数组。



首先,我想把它们全部转换成dict,所以我可以创建一个dict数组。



其次,我想从该数组中获取所有的foo值,所以我可以创建一个foo数组。



管理这个?



谢谢,

解决方案

're after?

  import ast 
import numpy
a = numpy.array([{'foo ':123},{'foo':234}])
numpy.fromiter((ast.literal_eval(s)['foo'] for a in a),numpy.int_)
/ b

$ b

(当然相应的dtype将取决于这些dict中的实际情况。)


With the following expression, you can convert a string to a python dict.

>>> import ast
>>> a = ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}")
>>> a
{'muffin': 'lolz', 'foo': 'kitty'}

And with the following expression, you can get the "foo" value:

>>> a.get('foo')

I have an array of strings which are similar to python dict format.

Firstly, I want to convert all of them to dict, so I will be able to create a dict array.

Secondly, I want to get all "foo" values from that dict array, so I will be able to create a "foo" array.

How can I manage this?

Thanks,

解决方案

Is this approximately what you're after?

import ast
import numpy
a = numpy.array(["{'foo':123}","{'foo':234}"])
numpy.fromiter((ast.literal_eval(s)['foo'] for s in a), numpy.int_)

(Of course the appropriate dtype will depend on what's actually in those dicts.)

这篇关于在numpy数组上实现ast.literal_eval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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