我需要检查两个列表之间是否缺少项目。请告诉我支票中有哪些帐户,而不是account_codes列表中的帐户。我想我在这里需要正则表达式。
Account_codes = ['55555', '000002255a1', '98123a026', '4561b', '0000012e5', '987654321']
Check = ['55555', '2255a1', '123a', '0004561b', '00000012e56', '0987654321']
如您所见,我的困难是双方的数据都不相同。填充似乎在某个时候发生,然后停止。有些数据用零填充,有些则不是。实际数据集很大,因此我需要在任何解决方案中都牢记这一点。
我立即想到的是像这样从两侧去除所有前导零:
stripped_acct = [item.lstrip('0') for item in Account_codes]
stripped_check = [item.lstrip('0') for item in Check]
matches = []
missing_from_acct = []
for item in stripped_check:
if item in stripped_acct:
matches.append(item)
else:
missing_from_account.append(item)
是否有更好的解决方案来解决此问题,或者您发现现有代码中是否存在效率低下的问题?
答案 0 :(得分:1)
集合对于此类操作最有效:
a_set = set([i.lstrip('0') for i in Account_codes])
c_set = set([i.lstrip('0') for i in Check])
list(c_set - a_set)
>> ['123a', '12e56']
答案 1 :(得分:0)
尝试以下方法:
missing_from_account = list(set([item.lstrip('0') for item in Check])-set([item.lstrip('0') for item in Account_codes]))
matches = list(set([item.lstrip('0') for item in Check]).intersection(set([item.lstrip('0') for item in Account_codes])))
答案 2 :(得分:0)
我将使用正则表达式删除主字符串前面的所有“ 0”,然后使用差异集找出我错过的内容。
import re
Account_codes = ['55555', '000002255a1', '98123a026', '4561b', '0000012e5', '987654321']
Check = ['55555', '2255a1', '123a', '0004561b', '00000012e56', '0987654321']
Check_nozero = [re.findall(r"([0]+|0?)(\w+)",ele)[0][-1] for ele in Check]
Account_codes_nozero = [re.findall(r"([0]+|0?)(\w+)",ele)[0][-1] for ele in Account_codes]
print( list(set(Check_nozero) - set(Account_codes_nozero)) )