python - 如果列表中的值以某些字符开头,则使用列表理解替换它们
问题描述
我有一个以下列表,我正在尝试替换以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']
结果列表仅包含替换的项目,而不是整个列表。如何使用上述方法获取完整列表?
解决方案
您需要在三元运算符中包含 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']
推荐阅读
- r - 如何编写正则表达式模式以从银行对帐单中的 AMT 提款交易中提取位置
- oracle - Oracle 的 JDBC 连接字符串未连接
- elasticsearch - elasticsearch date_histogram 会检查间隔内的日期是否存在?如果是这样,会发生什么?如果对此没有任何错误处理
- sql - 将嵌套的(二)NOT IN转换成嵌套的(二)NOT Exists
- visual-studio-code - 是否可以为 VS Code 终端添加与我用于整个编辑器相同的主题
- mongodb - mongodb 启动时自动关闭
- python - 如何使用箱线图检测和删除数据集中的异常值?
- bigcommerce - 使用隐身登录时 Facebook 页面插件无法正常工作
- c++ - 如何打印具有最低ascii和其他可能性的字符串
- google-fit - 用于计步的 Google Fit APi 授予第一次用户拒绝的权限