在检查重复项时将列表附加到另一个列表

2024-03-28 17:00:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一些帮助添加一个列表到另一个列表,同时检查重复。我只想将尚未存在的项目添加到基本列表中。你知道吗

我无法使用集合来完成此操作,因为基本列表中的项也是列表。你知道吗

我的基本列表示例如下:

toCrawl=[["http://website.html",0]["http://websiteAlt.html",1]["http://websiteAlt.html",1]]

我想添加的列表如下:

newLinks=["http://websiteAlt.html","http://websiteExample.html","http://websiteExampleAlt.html"]

因此,我想将“newLinks”列表添加到基本的“toCrawl”列表中,但是我只想在newLinks中的项还没有在toCrawl中时添加它。你知道吗

除此之外,我还想将“newLinks”中的项目作为列表添加到“toCrawl”列表中。因此,我不想在“newLinks”中添加如下项:"http://websiteExample.html",而是将其添加到列表中,例如:["http://websiteExample.html",0]


Tags: 项目http列表htmlwebsitetocrawlnewlinkswebsiteexamplealt
3条回答

这本词典很好,谢谢。不过,我最终选择了这种方法:

for link in newLinks:   #check every link in 'newLinks'
            if link not in toCrawl: #if the link is not in 'toCrawl'...
                toCrawl.append([link,depthFound+1]) #add the link to 'toCrawl' with the 'depthFound'

这可以用字典而不是单子来完成吗?你知道吗

toCrawlDict = dict(toCrawl)
for link in newLinks:
    if link not in toCrawlDict:
         toCrawlDict[link] = 0

一个很好的解决方案是使用列表理解并将列表转换为一个集合:

toCrawl=[["http://website.html",0],["http://websiteAlt.html",1],["http://websiteAlt.html",1]]
newLinks = set([item[0] for item in toCrawl])
print(newLinks)

输出

{'http://website.html', 'http://websiteAlt.html'}

请注意,为了删除重复项,集合似乎是一个很好的做法,这来自documentation

A set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. (For other containers see the built-in dict, list, and tuple classes, and the collections module.)

相关问题 更多 >