【问题标题】:Filtering a nested list without using a for loop?在不使用 for 循环的情况下过滤嵌套列表?
【发布时间】:2018-06-16 22:38:29
【问题描述】:

您好,有谁知道我是否可以过滤嵌套列表以仅返回每个子列表中的第二个值?我可以使用for循环来做到这一点,只是想知道是否可以使用过滤器方法?

weather_data = [['1', 'sunny'], ['2', 'rainy'], ['3', 'sunny']]

返回:

weather = ['sunny', 'rainy', 'sunny']

【问题讨论】:

    标签: python-3.x list filter nested


    【解决方案1】:

    如何使用列表推导:

    values = [x[1] for x in weather_data]
    print (values)
    

    【讨论】:

      【解决方案2】:

      假设您在问题中选择的snake_case 暗示了Python,请尝试map 函数:

      weather_data = [['1', 'sunny'], ['2', 'rainy'], ['3', 'sunny']]
      result = list(map(lambda x: x[1], weather_data))
      print(result)
      

      如果不是 Python,许多其他语言也有此功能,但语法略有不同:

      https://en.wikipedia.org/wiki/Map_(higher-order_function)#Language_comparison

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-29
        • 2021-11-04
        • 1970-01-01
        • 2019-05-18
        • 2021-08-12
        • 2021-09-06
        相关资源
        最近更新 更多