【问题标题】:Most Pyhthonic way to convert element of list get with re使用 re 转换列表元素的大多数 Pythonic 方法
【发布时间】:2015-11-05 04:50:05
【问题描述】:

我正在使用正则表达式从字符串 (lp) 中提取一些数字。我知道我将要从中得到的列表将仅包含 2 个元素。我也知道它们都是整数。

因此我想只用一行代码来写这个。

home,away = re.findall(r'\d+',lp)
home,away = int(home),int(away)

感谢您的帮助

【问题讨论】:

  • map(int, re.findall(r'\d+', lp)) ?
  • 谢谢。然后我会阅读更多关于地图的内容。再次感谢。

标签: python regex list integer


【解决方案1】:

您可以使用以下内容:

home, away = map(int, re.findall(r'\d+', lp))

另一个想法是使用列表推导:

home, away = [int(e) for e in re.findall(r'\d+', lp)]

当你有一个静态结果长度时管理类型的小技巧:

expected_types = [int, int, str]
elements = ['1', '2', 'toto']

result = [_type(e) for _type, e in zip(exected_types, elements]
# Returns : [1, 2, 'toto']

【讨论】:

  • 谢谢。 Tu viens d ajouter le soleil de Pau dans mon code ;)
【解决方案2】:

另一种解决方案:

home, away = [ int(x) for x in re.findall(r'\d+', lp) ]

编辑:FunkySayu 你更快...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    • 2011-12-11
    • 2017-09-12
    • 2010-11-27
    • 2019-01-25
    • 2012-10-15
    • 1970-01-01
    相关资源
    最近更新 更多