首页 > 解决方案 > 如果列表中的值以某些字符开头,则使用列表理解替换它们

问题描述

我有一个以下列表,我正在尝试替换以23:to开头的任何值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']

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

标签: pythonlistif-statementlist-comprehensionconditional-operator

解决方案


您需要在三元运算符中包含 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']

推荐阅读