伙计们!
我有一个很大的字符串列表(len > 1000000),我正在尝试将其转换为数据帧。在此之前,我必须排除一些长度为 20~22 位数字的项目(例如:0000000011111216546546),因为它们对我的数据框来说是一个问题。
我用下面的代码完成了这个工作,我知道它不是 pythonic(并且需要 20 分钟才能运行):
for i in range(len(lines2)):
if re.match(r'(?:(?<!\d)\d{20,30}(?!\d))', lines2[i]):
exclusao2.append(lines2[i])
lines2 = [x for x in lines2 if x not in exclusao2]
这里有人知道如何在较短的时间内做到这一点吗?
提前致谢。
您的代码速度很慢,因为您正在构建一个列表,然后使用它来检查成员资格。从列表中重复测试成员资格是低效的。
假设您有 1% 的值需要删除,这将为您提供
exclusao2
中的 10k 个字符串。然后,对于其中的每一个,您将测试您的列表理解中的成员资格。这很慢。
为了改进你的代码,你需要使用一套。
exclusao2 = set()
for s in lines2:
if re.match(r'(?:(?<!\d)\d{20,30}(?!\d))', s):
exclusao2.add(s)
lines2 = [x for x in lines2 if x not in exclusao2]
但这仍然不理想。
您可以直接使用您的测试:
lines2 = [s for s in lines2 if not re.match(r'(?:(?<!\d)\d{20,30}(?!\d))', s)]
更好的是,由于您的检查非常简单,请避免使用正则表达式,按照评论中的建议使用字符串操作:
lines2 = [s for s in lines2
if not (s.isdigit() and (20 <= len(s) <= 22))]