0

如果我创建两个包含这样的列表的列表:

bad_list.append(['blue_widget', 'cracked', '776'])
bad_list.append(['red_widget', 'not_smooth', '545']) 
bad_list.append(['yellow_widget', 'spots', '35']) 
bad_list.append(['green_widget', 'smells_bad', '10'])
bad_list.append(['purple_widget', 'not_really_purple', '10'])


good_list.append(['blue_widget', 'ok', '776'])
good_list.append(['red_widget', 'ok', '545']) 
good_list.append(['green_widget', 'ok', '10'])

我希望能够使用列表理解来比较两个列表,并使用第一个元素(x_widget)作为要比较的项目来删除好列表中存在的坏列表中的所有项目。使用上面的示例,我应该留下:

['yellow_widget', 'spots', '35']
['purple_widget', 'not_really_purple', '10']

我尝试使用列表理解并且它有效,但新列表不保留每一行:

final_list = [x for x in bad_list[0] if x not in good_list[0]]

当我在 final_list 中使用 for item 打印出内容时,我得到如下信息:

yellow_widget
smells_bad
10

任何线索将不胜感激。

4

5 回答 5

1

一个班轮

[x for x in bad_list if any(x[0] == y[0] for y in good_list)]

*感谢@Bakuriu

于 2013-10-25T16:36:46.243 回答
0

最简单的方法是:

final_list = [x for x in bad_list if x[0] not in [x[0] for x in good_list]]

但请注意,测试一个元素是否存在于列表中并不是那么有效。

因此,您可以先构建一个集合:

good_list_names = set([x[0] for x in good_list])

接着:

final_list = [x for x in bad_list if x[0] not in good_list_names]
于 2013-10-25T16:32:05.987 回答
0

有一个更有效的解决方案。从您的列表中制作一组

bad_set = set(bad_list)
good_set = set(good_list)

现在要删除好列表中存在的坏列表中的所有项目,您可以简单地减去集合:

bad_set - good_set

如果您愿意,可以将集合转换回列表。

于 2013-10-25T16:28:15.747 回答
0

没有以任何方式真正优化,但这应该可以工作:http ://codecube.io/AD7RHA

bad_list=[]
good_list=[]

bad_list.append(['blue_widget', 'cracked', '776'])
bad_list.append(['red_widget', 'not_smooth', '545']) 
bad_list.append(['yellow_widget', 'spots', '35']) 
bad_list.append(['green_widget', 'smells_bad', '10'])
bad_list.append(['purple_widget', 'not_really_purple', '10'])


good_list.append(['blue_widget', 'ok', '776'])
good_list.append(['red_widget', 'ok', '545']) 
good_list.append(['green_widget', 'ok', '10'])

# ['yellow_widget', 'spots', '35']
# ['purple_widget', 'not_really_purple', '10']

labels = zip(*good_list)[0]

new_bad_list=[]

for item in bad_list:
    if item[0] not in labels:
        new_bad_list.append(item)

print new_bad_list

或者这个单行:

new_bad_list=[item for item in bad_list if item[0] not in zip(*good_list)[0]]
于 2013-10-25T16:26:05.493 回答
0

尝试这个:

print [ele for ele in bad_list if ele[0] not in [i[0] for i in good_list]]

输出:

[['yellow_widget', 'spots', '35'], ['purple_widget', 'not_really_purple', '10']]
于 2013-10-25T16:27:07.007 回答