【问题标题】:Python Filtering two lists by values in one listPython按一个列表中的值过滤两个列表
【发布时间】:2020-04-26 18:20:20
【问题描述】:

我正在尝试通过 x 坐标的值过滤一组 x,y 坐标,例如在以下代码中:

x_list = [-4,-4,-3,-2,-2,-1,-1,1,2,3,4]
y_list = [0,2,-4,-2,4,-1,3,1,3,-1,4]

new_x = []
new_y = []

for i,x in enumerate(x_list):

    if x <= some_value:

        new_x.append(x_list[i])
        new_y.append(y_list[i])

能否在一行中使用 lambda 表达式和 map,filter,zip 等函数更有效地执行此操作?

谢谢!

【问题讨论】:

    标签: python dictionary lambda filter zip


    【解决方案1】:

    你可以像这样使用 zip:

    for z in zip(x_list, y_list):
      print(z)
    # prints tuples (x, y)
    

    或者像这样:

    for x,y in zip(x_list, y_list):
      print(x)
      print(y)
    

    大家一起:

    points = [z for z in zip(x_list, y_list) if z[0] <= somevalue]
    

    【讨论】:

      【解决方案2】:

      使用 zip、过滤器和 lambda:

      result = list(filter(lambda item: item[0] <= some_value, zip(x_list,y_list)))
      

      您可以解压缩返回的 x_coordinate、y_coordinate 对列表:

      new_x, new_y = list(zip(*result))
      # new_x and new_y returned as tuple
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-20
        • 1970-01-01
        • 2013-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多