假设我们有一个id列表和一个包含仓库信息的字典列表。我们想要遍历id列表,查找与每个id对应的仓库信息,并将这些仓库的其他属性设置为一个新的列表。
下面是一个示例代码:
id_list = [1, 2, 3]
repo_list = [{'id': 1, 'name': 'repo1', 'language': 'Python'},
{'id': 2, 'name': 'repo2', 'language': 'Java'},
{'id': 3, 'name': 'repo3', 'language': 'JavaScript'}]
other_attributes_list = []
for id in id_list:
for repo in repo_list:
if id == repo['id']:
other_attributes_list.append(repo['name'])
other_attributes_list.append(repo['language'])
print(other_attributes_list)
输出结果为:
['repo1', 'Python', 'repo2', 'Java', 'repo3', 'JavaScript']
我们先定义了id_list和repo_list。然后遍历id_list,对于每个id,我们遍历repo_list,找到与id匹配的仓库信息。如果匹配成功,我们将仓库的其他属性(这里是'name'和'language')添加到其他属性列表中。
最后,我们打印出其他属性列表。
上一篇:遍历ID和数组的jQuery循环