0

任何人都知道如何使用列表理解执行以下代码?由于 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]
4

1 回答 1

0

对于这个特定的条件,您可以使用集合推导:

xs = [{'key':1},{'key':1},{'key':2}, {'key':2}]
y = {x['key'] for x in xs}

print y # {1,2}
于 2012-08-26T19:34:10.643 回答