一行“x = for ... if y not in x”

时间:2014-11-05 13:03:35

标签: python list-comprehension

我想将以下代码中的for... if分成一行:

cities = ["Berlin", "Berlin", "Berlin", "London"]

unique_cities = []

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

print unique_cities

我想象这样的事情:

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

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

我如何制作一个单行内容?

2 个答案:

答案 0 :(得分:1)

如果订单不重要,更简单的方法就是

unique_cities = list(set(cities))

答案 1 :(得分:1)

我认为把它变成一个集合会更容易:

unique_cities = set(cities)