Python如何从含Approved关键词的数组字符串中提取目标整数
从含指定关键词的数组元素中提取目标整数
需求说明
现有存储4个字符串元素的数组,需要仅从包含Approved关键词的字符串中提取末尾带3个0的整数。
测试数据
my_array = ['STK72184 4/28/2022 50 from Exchange Balance, 50 from Earning Balance & 10 from Bonus 25000 Regular 10/20/2023 Approved 4/28/2022', 'STK725721 4/27/2022 50 from Exchange Balance, 40 from Earning Balance & 10 from Bonus Balance 5000 Regular 10/19/2023 Closed 4/27/2022', 'STK725721 4/27/2022 50 from Exchange Balance, 40 from Earning Balance & 10 from Bonus Balance 15000 Regular 10/19/2023 Closed 4/27/2022', 'STK722222 4/26/2022 50 from Exchange Balance, 40 from Earning Balance & 10 from Bonus Balance 10000 Regular 10/18/2023 Approved 4/26/2022']
原有实现问题
原有代码未做关键词过滤,会遍历所有数组元素提取匹配值,输出结果不符合要求:
import re nums = [int(re.search(r'\d+000', s)[0]) for s in my_array] print(nums) # 输出: [25000, 5000, 15000, 10000]
预期输出
[25000,10000]
解决方案
在列表推导中增加筛选条件,只处理包含Approved的字符串即可,修正后代码:
import re nums = [int(re.search(r'\d+000', s)[0]) for s in my_array if 'Approved' in s] print(nums)
运行后即可得到预期输出。
鲁棒性优化:如果后续数据中存在带
Approved但无匹配整数的字符串,直接取[0]会抛出异常,可以改用如下写法规避报错:import re nums = [] for s in my_array: if 'Approved' not in s: continue match = re.search(r'\d+000', s) if match: nums.append(int(match.group()))
内容的提问来源于stack exchange,提问作者Rishi Pandey
相关产品推荐
相关产品推荐

