一种更简单的方式来引用所需字典(Python)的索引?

k4k*_*uz0 2 python for-loop

问题感觉它的措辞很差,如果你同意的话可以随意调整它,并且知道如何更好地表达它.

我有以下代码:

def owned_calendars(cal_items):
    """Returns only the calendars in which the user is marked as "owner"

    """
    owner_cals = []
    for entry in cal_items:
        if entry['accessRole'] == "owner":
            owner_cals.append(cal_items[cal_items.index(entry)])

    return owner_cals
Run Code Online (Sandbox Code Playgroud)

cal_itemslistdictionaries

在我写的行中,我owner_cals.append(cal_items[cal_items.index(entry)])试图附加具有该属性的字典accessRole = owner.

这条线似乎超长而且笨重,我想知道是否有更容易/更直观的方法来做到这一点?

Rah*_*pta 7

试试这个.您可以使用列表推导在一行中执行此操作.

owner_cals = [x for x in cal_items if x["access_role"]=="owner"]
Run Code Online (Sandbox Code Playgroud)

您也可以使用enumerate方法.

owner_cals = [j for i,j in enumerate(cal_items) if j["access_role"]=="owner"]
Run Code Online (Sandbox Code Playgroud)

另外,请记住.index()返回找到项目的最低索引.

["foo", "bar", "baz", "bar"].index("bar") 将永远返回1.