【问题标题】:Converting String to List [duplicate]将字符串转换为列表 [重复]
【发布时间】:2011-04-13 06:52:22
【问题描述】:

可能重复:
Converting a string that represents a list, into an actual list object.

你好,

我有一个这种格式的字符串:

>>> x="(174,185)"
>>> x
'(174,185)'

如何将此字符串转换为列表,以便可以将索引 0 作为 174 访问,将索引 1 作为 185 访问?我正在使用 Python 2.5 和 Win XP。 我尝试了几种方法,但效果不佳。感谢您的建议。 tq

>>> y=x.split(",")
>>> y
['(174', '185)']
>>> y[0]
'(174'
>>> [int(x) for x in x.split(",")]
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    [int(x) for x in x.split(",")]
ValueError: invalid literal for int() with base 10: '(174'
>>> 

【问题讨论】:

    标签: python string list python-2.5


    【解决方案1】:

    你可以试试这个

    y=x[1:-1].split(",")
    

    在拆分前去掉括号

    >>> x="(174,185)"
    >>> map(int, x[1:-1].split(','))
    [174, 185]
    

    如果你有python2.6+,你也可以使用literal_eval

    >>> from ast import literal_eval
    >>> literal_eval(x)
    (174, 185)
    >>> 
    

    【讨论】:

    • tq,这很好用!一旦进入列表,就可以访问索引。
    • 顺便说一句,x[1:-1] 是什么意思? tq
    • 是的,我明白你的意思,你只是把括号中的 int 值用逗号分隔。伟大的。 :)
    猜你喜欢
    • 2011-05-27
    • 2011-02-23
    • 2017-06-28
    • 2018-01-27
    • 2020-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    相关资源
    最近更新 更多