如何将字符串中的列表转换为列表 [英] How to convert a list within a string to a list

查看:93
本文介绍了如何将字符串中的列表转换为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典,其中一些值是列表.不幸的是,Python认为它们是字符串.该字典看起来像这样:

I have a dict where some of the values are lists. Unfortunately, Python thinks they are strings. The dict looks like this:

dict = {'key': 'x', 'key1': '[1, 2, 3], ...'}

当我拉 dict ['key1'] 并尝试对其执行列表操作时,我得到的回溯说我不能,因为该元素是字符串.没问题,但是将其从字符串转换为列表会分别转换字符串的每个字符.

When I pull dict['key1'] and try to perform list operations on it, I get tracebacks that say I can't because the element is a string. No problem, but converting it from a string to a list converts each character of the string separately.

list = list(dict['key1'])

>>> ['[', '1', ',' ' ', '2', ',', ' ', '3', ']']

如何转换字符串以将其作为列表类型?

how do I convert the string to get this as a list type?

>>> [1, 2, 3]

Python 2.5是必需的.

Python 2.5 is a requirement.

已更新:已更正,使列表成为字符串.更新2:包括用于生成字典的代码.它从XML源创建一个字典.

Updated: corrected to make the list a string. Update 2: includes code used to generate the dict. It creates a dict from an XML source.

class XmlDictConfig(dict):
def __init__(self, parent_element):
    if parent_element.items():
        self.updateShim(dict(parent_element.items()))
    for element in parent_element:
        if len(element):
            aDict = XmlDictConfig(element)
            if element.items():
                aDict.updateShim(dict(element.items()))
            self.updateShim({element.tag: aDict})
        elif element.items():
            self.updateShim({element.tag: dict(element.items())})
        else:
            self.updateShim({element.tag: element.text}) # WAS: _self.updateShim({element.tag: element.text.strip()})_ with strip(), the function will choke on some XML.

def updateShim (self, aDict ):
    for key in aDict.keys():
        if key in self:
            value = self.pop(key)
            if type(value) is not list:
                listOfDicts = []
                listOfDicts.append(value)
                listOfDicts.append(aDict[key])
                self.update({key: listOfDicts})
            else:
                value.append(aDict[key])
                self.update({key: value})
        else:
            self.update(aDict)

def flatten_dict(d):
    def expand(key, value):
        if isinstance(value, dict):
            return [ (key + '_' + k, v) for k, v in flatten_dict(value).items() ]
        else:
            return [ (key, value) ]

    items = [ item for k, v in d.items() for item in expand(k, v) ]

    return dict(items)

try:
    socket.setdefaulttimeout(15)
    f = urllib2.urlopen(xmlAddress)
    data = str(f.read())
    f.close()
    xmlRawData = re.sub(' xmlns="[^"]+"', '', data, count=1)
    root = ElementTree.XML(xmlRawData)

except:
    print "Something went very wrong."

xmlDict = XmlDictConfig(root)
flatxmlDict = flatten_dict(xmlDict)
finalDict = {}

for (key, value) in flatxmlDict.items():
    finalDict[key] = str(value)

推荐答案

如果您的意思是拥有这样的字典:

If you mean you have a dictionary like this:

dct = {'key': 'x', 'key1': '[1, 2, 3]'}

您可以使用 ast.literal_eval 将列表的字符串表示形式转换为实际列表:

you can use ast.literal_eval to make make the string representation of a list into an actual list:

>>> from ast import literal_eval
>>> dct = {'key': 'x', 'key1': '[1, 2, 3]'}
>>> dct['key1'] = literal_eval(dct['key1'])
>>> dct
{'key': 'x', 'key1': [1, 2, 3]}
>>> type(dct['key1'])
<class 'list'>
>>>

当然,最好调查一下为什么首先将列表做成字符串,然后改成字符串.

Of course, it would probably be better to investigate why the list is being made into a string in the first place and then fix that instead.

这篇关于如何将字符串中的列表转换为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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