列表中的python搜索值

列表中的python搜索值,python,Python,我是python新手。我有这样一个列表:“一级链接”: 现在我想搜索一个链接,例如/author/Albert Einstein。如果链接不存在,我想将其附加到列表中,否则什么也不做。一种方法是将其转换为包含所有“链接”字段的列表,然后在中使用,例如: mylinks = [ { "type" : "np", "link_id" : "quotes-first-1", "link" : "/login" }, {

我是python新手。我有这样一个列表:
“一级链接”


现在我想搜索一个链接,例如/author/Albert Einstein。如果链接不存在,我想将其附加到列表中,否则什么也不做。

一种方法是将其转换为包含所有“链接”字段的列表,然后在中使用
,例如:

mylinks = [
    {
        "type" : "np",
        "link_id" : "quotes-first-1",
        "link" : "/login"
    },
    {
        "type" : "np",
        "link_id" : "quotes-first-2",
        "link" : "/author/Albert-Einstein"
    }]

for element in mylinks:
    if element['link'] == "/author/Albert-Einstein":
        print(element)
        # do whatever with element or element's attr e.g element['type']...
mylinks = [
    {
        "type" : "np",
        "link_id" : "quotes-first-1",
        "link" : "/login"
    },
    {
        "type" : "np",
        "link_id" : "quotes-first-2",
        "link" : "/author/Albert-Einstein"
    }]

if "/author/Albert-Einstein" in [ x["link"] for x in mylinks ]:
    print("Found it!")
else:
    print("Not there...")
    # Append your new object
    mylinks.append({...})

谢谢@shahaf,但这会占用更多的时间,因为我有大量的数据。@bhattraideb如果列表没有排序或散列,你就没有其他选择来迭代整个列表,并且上面所有其他版本的代码都不会获得太多性能,基本上与我的情况相同,列表存储在mongoDB上,如果以前没有存储,则必须添加链接。谢谢。@bhattraideb建议您将其更改为mongodb问题。。因为你可以在数据库本身上查询它,比得到所有结果并迭代它们要快得多……我看不出另一个答案比这个答案快多少。它们都迭代整个列表。另一个只是把它放在一个列表中。然后,它必须在
中对
再次进行迭代。好极了@urban,我正在搜索像这样更快的东西。非常感谢。最好将数据创建为键入
链接
的dict,尽管我怀疑此dict将无法用于任何其他用途。
mylinks = [
    {
        "type" : "np",
        "link_id" : "quotes-first-1",
        "link" : "/login"
    },
    {
        "type" : "np",
        "link_id" : "quotes-first-2",
        "link" : "/author/Albert-Einstein"
    }]

if "/author/Albert-Einstein" in [ x["link"] for x in mylinks ]:
    print("Found it!")
else:
    print("Not there...")
    # Append your new object
    mylinks.append({...})