【问题标题】:How to map all numbers in a string to a list in Python? [duplicate]如何将字符串中的所有数字映射到 Python 中的列表? [复制]
【发布时间】:2013-03-22 16:12:28
【问题描述】:

假设我有一个字符串

"There are LJFK$(#@$34)(,0,ksdjf apples in the (4,5)"  

我希望能够将数字动态提取到列表中:[34, 0, 4, 5]
有没有简单的方法在 Python 中做到这一点?

换句话说,
有没有办法提取由任何分隔符分隔的连续数字簇?

【问题讨论】:

  • 如果字符串是"12.34",你想要[12, 34]还是[12.34]? IOW,你想要的只是连续数字的整数吗?
  • 在这种情况下,它将是 [12, 34],整数。当前答案按预期工作(我还不能接受)

标签: python string


【解决方案1】:

当然,使用regular expressions:

>>> s = "There are LJFK$(#@$34)(,0,ksdjf apples in the (4,5)"
>>> import re
>>> list(map(int, re.findall(r'[0-9]+', s)))
[34, 0, 4, 5]

【讨论】:

  • 使用列表推导通常比使用map 更可取。尤其是因为您只是将结果投射到列表中。
  • @Cairnarvon 通常是这样,除非您可以简单地调用现有函数(因为您不必弄清楚临时变量的名称)。列表创建只是为了漂亮的输出。如果你要迭代结果,你显然可以跳过它。
  • 您也可以使用\d+ 来表示正则表达式。
  • @Schoolboy 是的,但是必须使用比int 复杂得多的东西来支持٣٤ 之类的输入。
  • @phihag 为什么会这样??这些输入将如何通过过滤器??
【解决方案2】:

您也可以不使用正则表达式来执行此操作,但需要做更多工作:

>>> s = "There are LJFK$(#@$34)(,0,ksdjf apples in the (4,5)"
>>> #replace nondigit characters with a space
... s = "".join(x if x.isdigit() else " " for x in s)
>>> print s
                   34   0                      4 5
>>> #get the separate digit strings
... digitStrings = s.split()
>>> print digitStrings
['34', '0', '4', '5']
>>> #convert strings to numbers
... numbers = map(int, digitStrings)
>>> print numbers
[34, 0, 4, 5]

【讨论】:

  • 我想我比我打算提出的itertools.groupby 解决方案更喜欢这个。
  • 这也是一个很好的解决方案
猜你喜欢
  • 2023-03-26
  • 1970-01-01
  • 2013-09-14
  • 1970-01-01
  • 2016-05-12
  • 2019-08-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多