任何人都知道如何使用列表理解来执行以下代码?我因为if条件而陷入困境,我不知道如何使用列表理解来应用。提前谢谢。
x = [{'key':1},{'key':1},{'key':2}, {'key':2}]
y = []
for e in x:
if e['key'] not in y:
y.append(e['key'])
>>>print y
[1,2]
答案 0 :(得分:0)
对于此特定条件,您可以使用集合理解:
xs = [{'key':1},{'key':1},{'key':2}, {'key':2}]
y = {x['key'] for x in xs}
print y # {1,2}