return 个列表中的项目(如果不在另一个列表中)
return items from one list if not in the other
如果 Project
中的项目没有出现在我的任务列表 Task
中,我想 return 项目。我的代码只有 return 的所有内容,并且在 Project
中。我做错了什么?
Task = [['Task1','Project1',3],['Task2','Project4',6]]
Project = [['Project1', 'Andrew'],['Project2','Bob'],['Project3','Bob']]
not_in_list = [item for item in Project if item[0] not in Case]
print not_in_list
输出:
[['Project1', 'Andrew'], ['Project2', 'Bob'], ['Project3', 'Bob']]
预期结果:
[['Project2', 'Bob'],['Project3', 'Bob']]
这样就可以了:
Task = [['Task1','Project1',3],['Task2','Project4',6]]
Project = [['Project1', 'Andrew'],['Project2','Bob'],['Project3','Bob']]
no_tasks = [p for p in Project if all(p[0] not in t for t in Task)]
print no_tasks
但对于大型列表来说效率会非常低。是时候重新考虑您的数据结构了!
如果您可以假设项目名称始终位于任务的索引 1 中,则仅比之前的答案效率更高:
>>> Task = [['Task1','Project1',3],['Task2','Project4',6]]
>>> Project = [['Project1', 'Andrew'],['Project2','Bob'],['Project3','Bob']]
>>> assigned = [t[1] for t in Task]
>>> [p for p in Project if p[0] not in assigned]
[['Project2', 'Bob'], ['Project3', 'Bob']]
task = [['Task1','Project1',3],['Task2','Project4',6]]
project = [['Project1', 'Andrew'],['Project2','Bob'],['Project3','Bob']]
task_projects = set(pr for _, pr, _ in task)
not_in_list = [item for item in project if item[0] not in task_projects]
print not_in_list
(请注意,我更改了变量名称以使其符合建议。)
此代码首先创建一组存在的项目名称。检查集合中的项目是否存在比列表中的要便宜得多。
如果 Project
中的项目没有出现在我的任务列表 Task
中,我想 return 项目。我的代码只有 return 的所有内容,并且在 Project
中。我做错了什么?
Task = [['Task1','Project1',3],['Task2','Project4',6]]
Project = [['Project1', 'Andrew'],['Project2','Bob'],['Project3','Bob']]
not_in_list = [item for item in Project if item[0] not in Case]
print not_in_list
输出:
[['Project1', 'Andrew'], ['Project2', 'Bob'], ['Project3', 'Bob']]
预期结果:
[['Project2', 'Bob'],['Project3', 'Bob']]
这样就可以了:
Task = [['Task1','Project1',3],['Task2','Project4',6]]
Project = [['Project1', 'Andrew'],['Project2','Bob'],['Project3','Bob']]
no_tasks = [p for p in Project if all(p[0] not in t for t in Task)]
print no_tasks
但对于大型列表来说效率会非常低。是时候重新考虑您的数据结构了!
如果您可以假设项目名称始终位于任务的索引 1 中,则仅比之前的答案效率更高:
>>> Task = [['Task1','Project1',3],['Task2','Project4',6]]
>>> Project = [['Project1', 'Andrew'],['Project2','Bob'],['Project3','Bob']]
>>> assigned = [t[1] for t in Task]
>>> [p for p in Project if p[0] not in assigned]
[['Project2', 'Bob'], ['Project3', 'Bob']]
task = [['Task1','Project1',3],['Task2','Project4',6]]
project = [['Project1', 'Andrew'],['Project2','Bob'],['Project3','Bob']]
task_projects = set(pr for _, pr, _ in task)
not_in_list = [item for item in project if item[0] not in task_projects]
print not_in_list
(请注意,我更改了变量名称以使其符合建议。)
此代码首先创建一组存在的项目名称。检查集合中的项目是否存在比列表中的要便宜得多。