我有一份包含约1,300,000件物品的清单。例如,['。'','。b.a','。c.b','。f.c.b']。
我想删除子域名(例如上面列表中的“.b.a”和“.f.c.b”)。
我是新手。我想了解速度。以下是我的尝试,似乎很慢。任何建议:
# create separate lists, perhaps that is faster
a1 = []
b2 = []
c3 = []
d4 = []
e5 = []
f6 = []
for i in dupesgone:
j = i.count('.')
if j == 1:
a1.append(i)
elif j == 2:
b2.append(i)
elif j == 3:
c3.append(i)
elif j == 4:
d4.append(i)
elif j == 5:
e5.append(i)
else:
f6.append(i)
for a in a1:
la = -len(a)
for b in b2:
if a == b[la:]:
b2.remove(b)
for c in c3:
if a == c[la:]:
c3.remove(c)
for d in d4:
if a == d[la:]:
d4.remove(d)
--snip--
# how about this, is this faster
[b2.remove(b) for b in b2 for a in a1 if a == b[-len(a):]]
[c3.remove(c) for c in c3 for a in a1 if a == c[-len(a):]]
[d4.remove(d) for d in d4 for a in a1 if a == d[-len(a):]]
[e5.remove(e) for e in e5 for a in a1 if a == e[-len(a):]]
[f6.remove(f) for f in f6 for a in a1 if a == f[-len(a):]]
我应该创建字典吗?会更快吗?
感谢您的帮助。
答案 0 :(得分:2)
创建新列表通常比删除不匹配的项目更快:
dupesgone = [domain for domain in dupesgone if domain.count(".") == 1]
答案 1 :(得分:1)
实际上,我认为最快的算法是
以下是未经测试的代码草图:
def reverse(s):
return s[::-1]
r = map(reverse, devgone)
r.sort()
ci = None
out = []
for ni in r:
if not ci or not ni.startswith(ci):
out.append(ni)
ci = ni
return map(reverse, out)