我的数据结构是这样的:蟒蛇 - 搜索元素字典中的列表内
- testSet: a list of records in the test set, where each record
is a dictionary containing values for each attribute
而且在每个记录有一个名为“ID”的元素。我现在想通过ID值在testSet
内搜索记录。所以当我得到一个ID = 230的时候,我想返回它的ID元素等于230的记录。
我该怎么做?
我的数据结构是这样的:蟒蛇 - 搜索元素字典中的列表内
- testSet: a list of records in the test set, where each record
is a dictionary containing values for each attribute
而且在每个记录有一个名为“ID”的元素。我现在想通过ID值在testSet
内搜索记录。所以当我得到一个ID = 230的时候,我想返回它的ID元素等于230的记录。
我该怎么做?
next((x for x in testSet if x["ID"] == 230), None)
如果没有找到,将返回带有该ID的第一项或None
。
是这样的吗?
for record in testSet:
if record['ID'] == 230:
return record
例如为:
set = [{'ID': 50}, {'ID': 80}]
def find_set(id):
return [elem for elem in set if elem['ID'] == id]
这将返回指定ID的所有项目。如果您只想要第一个,请添加[0](检查后是否存在,例如:
def find_set(id):
elems = [elem for elem in set if elem['ID'] == id]
return elems[0] if elems else None