【问题标题】:Filter List items in Python [duplicate]Python中的过滤列表项[重复]
【发布时间】:2018-06-09 17:35:07
【问题描述】:

我需要从城市列表中删除不超过 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)

【问题讨论】:

    标签: python python-3.x list filter


    【解决方案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 然后将包含长度小于 6 的城市。

    【讨论】:

    • 最短的?在我的回答中? :D 最多,我会说它们是相似的。
    • 是的,你是对的,列表推导比使用过滤器和 lambda 函数更容易阅读。
    【解决方案2】:

    你可以使用过滤器:

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

    【讨论】:

      猜你喜欢
      • 2012-12-12
      • 2013-11-28
      • 1970-01-01
      • 1970-01-01
      • 2016-03-03
      • 2020-01-16
      • 2018-01-29
      • 1970-01-01
      • 2016-10-23
      相关资源
      最近更新 更多