【问题标题】:split a string of numbers into a list [duplicate]将一串数字拆分成一个列表[重复]
【发布时间】:2021-01-30 10:41:59
【问题描述】:

我有一串数字列表,如下所示: (整个List存储为字符串)

"[{'3', '4', '10', '11'}, {'13', '16', '17', '19'}]"

我只想选择数字并将它们分配到一个列表中,就像这样

['3', '4', '10', '11', '13', '16', '17', '19']

我尝试使用 split() 但我得到以下结果:

['3', '4', '1', '0', '1', '1', '1', '3', '1', '6', '1', '7', '1', '9']

请问我该怎么做。

【问题讨论】:

  • 你同时问了两件事。链接的问题包含第一个问题的答案。
  • 或者,如果您不关心数据结构,问题的解决方案如下所示:stackoverflow.com/questions/4289331/…

标签: python string list split


【解决方案1】:

regex救援

文档:https://docs.python.org/3/library/re.html#re.findall

# coding=utf8

import re

regex = r"[0-9]+"

test_str = "\"[{'3', '4', '10', '11'}, {'13', '16', '17', '19'}]\""

print(re.findall(regex, test_str, re.MULTILINE))
['3', '4', '10', '11', '13', '16', '17', '19']

【讨论】:

  • 是的,谢谢。但是如果我想让每个部分像这样分开呢:['3', '4', '10', '11'] ['13', '16', '17', '19'] !跨度>
猜你喜欢
  • 2016-03-24
  • 1970-01-01
  • 1970-01-01
  • 2019-03-14
  • 2021-06-27
  • 2012-10-23
  • 1970-01-01
  • 2021-04-05
  • 2013-04-15
相关资源
最近更新 更多