我有 4 個元素存盤在一個陣列中,我只想從提到Approved關鍵字的字串中獲取整數。
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
# Print integers
nums = [int(re.search(r'\d 000', s)[0]) for s in my_array]
print(nums)
# Printed output:
# [25000, 5000, 15000, 10000]
預期輸出為:
[25000,10000]
uj5u.com熱心網友回復:
將串列推導與re.search和 一起使用if。請注意,第二個示例表明基于正則運算式的搜索在提取您想要的模式方面非常強大,因此我幾乎總是更喜歡它而不是精確字串匹配(除非性能至關重要)。另外,我重命名array為lst(這個資料結構在 Python 中稱為 list,而 array 是其他一些語言)。
import re
my_lst = ['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']
nums = [int(re.search(r'\d 000', s)[0]) for s in my_lst if re.search(r'Approved', s)]
print(nums)
# [25000, 10000]
nums = [int(re.search(r'\d 000', s)[0]) for s in my_lst if re.search(r'4/2[67]', s)]
print(nums)
# [5000, 15000, 10000]
uj5u.com熱心網友回復:
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
# Print integers
nums = [int(re.search(r'\d 000', s)[0]) for s in my_array if 'Approved' in s]
print(nums) # [25000, 10000]
uj5u.com熱心網友回復:
您可以過濾所需的數字而無需重新。只需使用next()功能搜索所需的號碼。這假設在每個元素中都有一個以“000”結尾的整數my_array(這個假設也在你的原始代碼中做出,所以我假設它沒問題)。
# search a string that ends with '000' among the words in each element that includes "Approved" in my_array
[int(next(i for i in s.split() if i[-3:]=='000')) for s in my_array if 'Approved' in s]
# [25000, 10000]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/492577.html
下一篇:在某個符號最后一次出現后切斷字串
