【发布时间】:2020-06-10 04:26:52
【问题描述】:
我有这个 (python) 列表
my_list = [['dog','cat','mat','fun'],['bob','cat','pan','fun'],['dog','ben','mat ','老鼠'],
['cat','mat','fun','dog'],['mat','fun','dog','cat'],['fun','dog','cat','垫'],
['老鼠','狗','本','垫子'],['狗','垫子','猫','乐趣'], ...
]
my_list 有 200704 个元素
注意这里
my_list[0] = ['狗','猫','垫子','乐趣']
狗->猫->垫子->乐趣->狗
my_list[3] = ['cat','mat','fun','dog']
猫->垫子->乐趣->狗->猫
my_list[4] = ['mat','fun','dog','cat']
垫子->乐趣->狗->猫->垫子
my_list[5] = ['fun','dog','cat','mat']
有趣->狗->猫->垫子->有趣
循环往复,它们都是一样的。所以他们应该被标记为重复。
注意:
my_list[0] = ['狗','猫','垫子','乐趣']
my_list[7] = ['狗','垫子','猫','乐趣']
这些不应该被标记为重复,因为它们是循环的,它们是不同的。
同样,
my_list[2] = ['dog','ben','mat','rat']
my_list[6] = ['rat','dog','ben','mat']
它们应该被标记为重复。
def remove_circular_duplicates(my_list):
# the quicker and more elegent logic here
# the function should identify that my_list[0], my_list[3], my_list[4] and my_list[5] are circular duplicates
# keep only my_list[0] and delete the rest 3
# same for my_list[2] and my_list[6] and so on
return (my_list_with_no_circular_duplicates)
----------------------------------- -----------------
我的尝试:
-------------------------------------------------- --------------
这可行,但需要 3 个多小时才能完成 200704 个元素。
而且它也不是一种优雅的方式..(请原谅我的水平)
t=my_list
tLen=len(t)
while i<tLen:
c=c+1
if c>2000:
# this is just to keep you informed of the progress
print(f'{i} of {tLen} finished ..')
c=0
if (finalT[i][4]=='unmarked'):
# make 0-1-2-3 -> 1-2-3-0 and check any duplicates
x0,x1,x2,x3 = t[i][1],t[i][2],t[i][3],t[i][0]
# make 0-1-2-3 -> 2-3-0-1 and check any duplicates
y0,y1,y2,y3 = t[i][2],t[i][3],t[i][0],t[i][1]
# make 0-1-2-3 -> 3-0-1-2 and check any duplicates
z0,z1,z2,z3 = t[i][3],t[i][0],t[i][1],t[i][2]
while j<tLen:
if (finalT[j][4]=='unmarked' and j!=i):
#j!=i skips checking the same (self) element
tString=t[j][0]+t[j][1]+t[j][2]+t[j][3]
if (x0+x1+x2+x3 == tString) or (y0+y1+y2+y3 == tString) or (z0+z1+z2+z3 == tString):
# duplicate found, mark it as 'duplicate'
finalT[j][4]='duplicate'
tString=''
j=j+1
finalT[i][4] = 'original'
j=0
i=i+1
# make list of only those marked as 'original'
i=0
ultimateT = []
while i<tLen:
if finalT[i][4] == 'original':
ultimateT.append(finalT[i])
i=i+1
# strip the 'oritinal' mark and keep only the quad
i=0
ultimateTLen=len(ultimateT)
while i<ultimateTLen:
ultimateT[i].remove('original')
i=i+1
my_list_with_no_curcular_duplicates = ultimateT
print (f'\n\nDONE!! \nStarted at: {start_time}\nEnded at {datetime.datetime.now()}')
return my_list_with_no_circular_duplicates
我想要的是一种更快的方式来做同样的事情。
提前 Tnx。
【问题讨论】:
标签: python list duplicates logic circular-dependency