关于python:一行“x = for … if y not in x”

One line “x = for… if y not in x”

本问题已经有最佳答案,请猛点这里访问。

我想把下面代码中的for... if转换为一行:

1
2
3
4
5
6
7
8
9
cities = ["Berlin","Berlin","Berlin","London"]

unique_cities = []

for city in cities:
    if city not in unique_cities:
        unique_cities.append(c)

print unique_cities

我想是这样的:

1
unique_cities = [city for city in cities if city not in unique_cities]

这当然不起作用,因为循环中没有定义unique_cities

我怎样才能把这个做成一行呢?


我认为把它变成一套会更容易:

1
unique_cities = set(cities)

如果秩序不重要,那么更简单的方法就是

1
unique_cities = list(set(cities))