【问题标题】:Erasing everything from every element in a list except the first few numbers in those elements删除列表中每个元素的所有内容,除了这些元素中的前几个数字
【发布时间】:2014-12-29 15:02:57
【问题描述】:

我在 Python 中有一个如下所示的列表:

['29382 this is something', '2938535 hello there', '392835 dont care for this', '22024811 yup']

我需要这样处理它:

['29382', '2938535', '392835', '22024811']

我将如何继续这样做? 我想我可以使用 re,但我不知道如何在这种情况下应用它。

【问题讨论】:

  • StackOverflow 可以帮助您实施。请向我们展示您尝试做的事情或您的想法,特别是如果您可以包含一些代码。

标签: python regex list


【解决方案1】:

你不需要regex,你可以在列表理解中使用split

>>> l = ['29382 this is something', '2938535 hello there', '392835 dont care for this', '22024811 yup']

>>> [i.split(' ', 1)[0] for i in l]
['29382', '2938535', '392835', '22024811']

【讨论】:

  • 谢谢!它可以完成工作,但我不太明白它是如何工作的。
  • @Michel 什么让你感到困惑,split 函数还是列表理解?
  • @Cyber​​ 列表理解
  • @Michel 列表推导本质上只是替换 for 循环的简洁方法。 See here。它们非常强大、干净且像 Python 一样,因此绝对值得学习。
【解决方案2】:

类似

>>> l=['29382 this is something', '2938535 hello there', '392835 dont care for this', '22024811 yup']
>>> import re
>>> [ re.sub(r'\D', '', x) for x in l]
['29382', '2938535', '392835', '22024811']

【讨论】:

    猜你喜欢
    • 2014-04-02
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    • 2021-06-26
    • 2020-01-01
    • 2022-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多