[英]An easier way of referring to the index of a desired dictionary (Python)?
Question feels like it's phrased poorly, feel free to adjust it if you agree and know how better to phrase it. 问题感觉它的措辞很差,如果你同意的话可以随意调整它,并且知道如何更好地表达它。
I have the following code: 我有以下代码:
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
is a list
of dictionaries
cal_items
是一个dictionaries
list
In the line where I have written owner_cals.append(cal_items[cal_items.index(entry)])
I'm trying to append the dictionaries that have the property accessRole = owner
. 在我编写
owner_cals.append(cal_items[cal_items.index(entry)])
我正在尝试附加具有属性accessRole = owner
的字典。
The line just seems super long and clunky, and I'm wondering if there's an easier/more intuitive way to do it? 这条线似乎超长而且笨重,我想知道是否有更容易/更直观的方法来做到这一点?
Try this. 尝试这个。 You can do this in one line using list comprehension .
您可以使用列表推导在一行中执行此操作。
owner_cals = [x for x in cal_items if x["access_role"]=="owner"]
You can also use enumerate
method. 您还可以使用
enumerate
方法。
owner_cals = [j for i,j in enumerate(cal_items) if j["access_role"]=="owner"]
Also, remember .index()
returns the lowest index where item is found . 另外,请记住
.index()
返回找到item的最低索引 。
["foo", "bar", "baz", "bar"].index("bar")
will always return 1. ["foo", "bar", "baz", "bar"].index("bar")
将始终返回1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.