list - python - 在列表中,查找项目结尾的重复项

82 4

我想在列表中找到在字符串的最后3个字符内有重复结尾的项目

使用以下代码,我只能识别列表中的完全重复项:


names = [\"tom\",\"john\",\"sara\" ,\"tamara\" ,\"tom\"]


single_finds = []


duplicate_finds = []



for i in names:


 if i in single_finds:


 duplicate_finds.append(i)


 else:


 single_finds.append(i)



print (single_finds)


print (duplicate_finds)



输出:


[\'tom\', \'john\', \'sara\', \'tamara\']


[\'tom\']



时间: 原作者:

104 2

一种方法是使用itertools.groupby,指定根据key参数的最后一个n字符来进行分组。

然后,我们可以使用itertools.chain,使用1对列表进行平滑,并删除重复:


from itertools import groupby, chain


k = lambda x: x[-3:]


l = [list(v) for _,v in groupby(sorted(names, key=k), key=k)]


# [[\'tamara\', \'sara\'], [\'john\'], [\'tom\', \'tom\']]


[i[0] for i in l if len(i) > 1]


# [\'tamara\', \'tom\']



原作者:
54 5


import itertools



names = [\"tom\",\"john\",\"sara\" ,\"tamara\" ,\"tom\"]



def find_duplicates(names):


 for key, group in itertools.groupby(sorted(names), lambda x: x[-3:]):


 grouped_items = list(group)


 if len(grouped_items) > 1:


 yield grouped_items[0]



def find_single(names):


 for key, group in itertools.groupby(sorted(names)):


 if len(list(group)) == 1:


 yield key



single_finds = list(find_single(names))


duplicate_finds = list(find_duplicates(names))



print (\"Single finds\", single_finds)


print (\"Duplicate finds\", duplicate_finds)



输出:


Single finds [\'john\', \'sara\', \'tamara\']


Duplicate finds [\'sara\', \'tom\']



原作者:
110 2


import collections


res=collections.defaultdict(list)



for name in names: 


 res[name[-3:]].append(name)



singles,dummies= [],[]



for v in res.values():


 singles.extend(v[:1])


 dummies.extend(v[1:])



然后:


singles is [\'tom\', \'john\', \'sara\']



dummies is [\'tom\', \'tamara\'] 



原作者:
...