过滤Python中的列表项

时间:2018-06-09 09:28:14

标签: python python-3.x list filter

我需要从城市列表中删除5个字符或更少字符的城市名称:

下面的代码有效,但我觉得代码太长了,我应该用另一种方法来减少代码的长度。

cities = ["New York", "Shanghai", "Munich", "Tokyo", "Dubai", "Mexico 
City", "São Paulo", "Hyderabad"]
count = 0
loop = 0

print("City List:",cities)

for x in range(len(cities)):
    if len(cities[x]) <= 5:
        cities[x] = 'small'

for x in range(len(cities)):
    if cities[x] == 'small':
        count += 1

while loop < count:
    for x in cities:
        if x == 'small':
            cities.remove(x)
            loop += 1

print("Filtered:",cities)

2 个答案:

答案 0 :(得分:1)

最短的方式是列表理解

cities = [city for city in cityes if len(city) < 6]

这与

等效
cities_filterd = []
for city in cities:
    if len(city) < 6:
        cities_filterd.append(city)

cities_filterd将包含lenth小于6的citiey。

答案 1 :(得分:0)

您可以使用过滤器:

filtered_cities = list(filter(lambda x: len(x) > 5, cities)