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

时间:2017-11-07 14:33:33

标签: python list duplicates append

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

我无法使用集合执行此操作,因为基本列表中的项目也是列表。

我的基本列表的一个例子如下:

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]

3 个答案:

答案 0 :(得分:1)

这可以用字典而不是列表来完成吗?

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

答案 1 :(得分:1)

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

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

  

set对象是不同的hashable对象的无序集合。   常见用途包括成员资格测试,从中删除重复项   序列,并计算数学运算,如交集,   联合,差异和对称差异。 (对于其他容器,请参阅   内置的dict,list和tuple类以及集合   模块。)

答案 2 :(得分:0)

词典是一个很好的感谢谢谢。然而,我最终选择了这种方法:

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'