【问题标题】:Replace values in list if they start with certain characters using a list-comprehension如果列表中的值以某些字符开头,则使用列表理解替换它们
【发布时间】:2020-05-30 06:55:36
【问题描述】:

我有一个以下列表,我正在尝试将任何以 23: 开头的值替换为 00:00:00.00

tc = ['00:00:00.360',
      '00:00:00.920',
      '00:00:00.060',
      '00:00:02.600',
      '23:59:55.680',
      '00:00:05.960',
      '00:00:01.040',
      '00:00:01.140',
      '00:00:01.060',
      '00:00:01.480',
      '00:00:00.140',
      '00:00:00.280',
      '23:59:59.800',
      '00:00:01.200',
      '00:00:00.400',
      '23:59:59.940',
      '00:00:01.220',
      '00:00:00.380']

我能够使用正则表达式得到我需要的东西,

tc = [re.sub(r'(\b23:)(.*)',r'00:00:00.00', item) for item in tc]

它给了我预期的结果,如下所示,

['00:00:00.360',
 '00:00:00.920',
 '00:00:00.060',
 '00:00:02.600',
 '00:00:00.00',
 '00:00:05.960',
 '00:00:01.040',
 '00:00:01.140',
 '00:00:01.060',
 '00:00:01.480',
 '00:00:00.140',
 '00:00:00.280',
 '00:00:00.00',
 '00:00:01.200',
 '00:00:00.400',
 '00:00:00.00',
 '00:00:01.220',
 '00:00:00.380']

但是如果我使用下面的方法而不使用正则表达式,那么结果不是我所期望的,

tc = [item.replace(item, '00:00:00.00') for item in tc if item.startswith('23:')]

结果:

['00:00:00.00', '00:00:00.00', '00:00:00.00']

结果列表仅包含替换的项目,而不是整个列表。如何使用上述方法获取完整列表?

【问题讨论】:

  • 这与您的问题没有直接关系,但是some_string.replace(some_string, whatever) 没有多大意义,因为它完全替换了字符串。你也可以自己写whatever。因此,对于您的最终代码示例,这将是 tc = ['00:00:00.00' for item in tc if item.startswith('23:')]

标签: python list if-statement list-comprehension conditional-operator


【解决方案1】:

您需要在三元运算符中包含一个 else 语句:

>>> [item.replace(item, '00:00:00.00') if item.startswith('23:') else item for item in tc]
['00:00:00.360',
 '00:00:00.920',
 '00:00:00.060',
 '00:00:02.600',
 '00:00:00.00',
 '00:00:05.960',
 '00:00:01.040',
 '00:00:01.140',
 '00:00:01.060',
 '00:00:01.480',
 '00:00:00.140',
 '00:00:00.280',
 '00:00:00.00',
 '00:00:01.200',
 '00:00:00.400',
 '00:00:00.00',
 '00:00:01.220',
 '00:00:00.380']

甚至只是:

>>> ['00:00:00.00' if item.startswith('23:') else item for item in tc]
['00:00:00.360',
 '00:00:00.920',
 '00:00:00.060',
 '00:00:02.600',
 '00:00:00.00',
 '00:00:05.960',
 '00:00:01.040',
 '00:00:01.140',
 '00:00:01.060',
 '00:00:01.480',
 '00:00:00.140',
 '00:00:00.280',
 '00:00:00.00',
 '00:00:01.200',
 '00:00:00.400',
 '00:00:00.00',
 '00:00:01.220',
 '00:00:00.380']

【讨论】:

    猜你喜欢
    • 2021-11-22
    • 2021-09-16
    • 1970-01-01
    • 2022-11-19
    • 2019-08-11
    • 2019-09-17
    • 1970-01-01
    • 2017-07-29
    • 2015-04-24
    相关资源
    最近更新 更多