繁体   English   中英

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

[英]An easier way of referring to the index of a desired dictionary (Python)?

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

我有以下代码:

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

cal_items是一个dictionaries list

在我编写owner_cals.append(cal_items[cal_items.index(entry)])我正在尝试附加具有属性accessRole = owner的字典。

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

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

owner_cals = [x for x in cal_items if x["access_role"]=="owner"]

您还可以使用enumerate方法。

owner_cals = [j for i,j in enumerate(cal_items) if j["access_role"]=="owner"]

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

["foo", "bar", "baz", "bar"].index("bar")将始终返回1。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM