Skip to main content
 首页 » 编程设计

python之如果一个值多次出现,则从列表中删除两项 (Python)

2025年05月04日10softidea

Python: How to remove all duplicate items from a list

大家好

我有一个(文件、 inode 、图像、散列)元组列表。如果它们具有相同的哈希值,我需要删除这两个项目。我没有那么多的编程经验,所以也许提示我必须看的东西已经很有帮助了。 我已经在网上搜索过了,但我唯一找到的是 this . 到目前为止,我想出了这个(非常尴尬的)解决方案:

        hashlist = {} 
        files_tobe_removed = [] 
        for (file, inode, image, hash) in self.files_for_json: 
            hashlist[hash] = 0 
        for (file, inode, image, hash) in self.files_for_json: 
            hashlist[hash] +=1 
        for (k,v) in hashlist.iteritems(): 
            if v == 2: 
                files_tobe_removed.append(k) 
        for (file,inode,image,hash) in self.files_for_json: 
            if hash in files_tobe_removed: 
                path = self.outDir + file 
                os.remove(path) 
                self.files_for_json.remove((file,inode,image,hash)) 

任何帮助将不胜感激。提前致谢

请您参考如下方法:

>>> from collections import Counter 
>>> L=[1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,1,2,3] 
>>> [k for k,v in Counter(L).items() if v==1] 
[7, 8, 9] 

澄清一下:

hash_counter = Counter(x[3] for x in self.files_for_json) 
for (file,inode,image,hash) in self.files_for_json: 
    if hash_counter[hash]>1: 
        # duplicated hash 
        ...