【问题标题】:Python string to list conversion [duplicate]Python字符串到列表转换[重复]
【发布时间】:2013-06-23 15:28:09
【问题描述】:

我有一个像这样的string

sample="[2, 6, 10, 14, 18, 22, 26, 30, 34, 38, 42, 46, 50]"

如何将其转换为 list?我希望输出是列表,像这样

output=[2, 6, 10, 14, 18, 22, 26, 30, 34, 38, 42, 46, 50]

我知道split() 功能,但在这种情况下,如果我使用

sample.split(',')

它将包含[] 符号。有什么简单的方法吗?

编辑对不起,重复的帖子..我直到现在才看到这个帖子 Converting a string that represents a list, into an actual list object

【问题讨论】:

  • output=json.loads(sample)?

标签: python string list type-conversion


【解决方案1】:

如果您要处理 Python 风格的类型(例如元组),您可以使用 ast.literal_eval

from ast import literal_eval

sample="[2, 6, 10, 14, 18, 22, 26, 30, 34, 38, 42, 46, 50]"

sample_list = literal_eval(sample)
print type(sample_list), type(sample_list[0]), sample_list
# <type 'list'> <type 'int'> [2, 6, 10, 14, 18, 22, 26, 30, 34, 38, 42, 46, 50]

【讨论】:

  • 好一个,乔恩,我不知道ast.literal_eval
【解决方案2】:

你可以在 python 中使用标准的字符串方法:

output = sample.lstrip('[').rstrip(']').split(', ')

如果您使用.split(',') 而不是.split(','),您将获得空格和值!

您可以使用以下方法将所有值转换为 int:

output = map(lambda x: int(x), output)

或将您的字符串加载为 json:

import json
output = json.loads(sample)

巧合的是,json 列表与 python 列表具有相同的符号! :-)

【讨论】:

  • 非常感谢!直到现在我才知道lstriprstrip.. 非常有用的东西。
  • @ChrisAung 实际上调用sample.strip('[]') 等价于sample.lstrip('[').rstrip(']')。大多数具有rl 版本的方法也有一个不带前缀的版本,适用于字符串的两端。
  • @Bakuriu 你说得对,但我更喜欢在可能的情况下明确说明,这样一个不是良好格式化列表的字符串就会中断。显式优于隐式 ;-)。
猜你喜欢
  • 2022-01-03
  • 2020-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-10
  • 2015-09-07
  • 2020-04-22
  • 2017-10-21
相关资源
最近更新 更多