代码之家  ›  专栏  ›  技术社区  ›  barciewicz

如何按指定条件对zip对象列表进行排序?

  •  0
  • barciewicz  · 技术社区  · 6 年前

    我编写了一个Airbnb scraper,它会遍历指定位置的每个家庭列表子页面,并为每个子页面返回zip对象,如下所示:

    subpage = zip(names, prices)
    

    在删除单个子页面之后,我添加 subpage 将对象压缩到列表:

    all_subpages.append(subpage)
    

    所以最后 all_subpages 是zip对象的列表,每个对象包含来自一个子页面的数据。

    我的问题是我想显示 所有子页面 在html表格中,我希望这些数据按价格排序。

    所以我的问题是:如何打印 所有子页面 按价格订购?

    预期产量:

        Name                 Price
        Apartment 3          10 GBP
        Apartment 1          15 GBP
        Apartment 2          20 GBP
    
        etc.
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Andrej Kesely    6 年前

    我对这个问题的看法是:

    from itertools import chain
    
    names = ['78', '1', '3']
    prices = ['15', '20', '10']
    
    names2 = ['82', '11', '33']
    prices2 = ['1', '2', '100']
    
    all_subpages = []
    
    subpage = zip(names, prices)
    all_subpages.append(subpage)
    
    subpage2 = zip(names2, prices2)
    all_subpages.append(subpage2)
    
    print('Home number\tprice')
    for (name, price) in sorted(chain.from_iterable(all_subpages), key=lambda v: int(v[1])):
        print(f'{name}\t\t{price} GBP')
    

    输出:

     Home number    price
    82      1 GBP
    11      2 GBP
    3       10 GBP
    78      15 GBP
    1       20 GBP
    33      100 GBP
    
        2
  •  1
  •   dawg    6 年前

    鉴于:

    l1=["Apartment 1", "Apartment 3","Apartment 2"]
    l2=['15 GBP','10 GBP','20 GBP'] 
    

    你可以在字典上对第二个元素进行排序,如下所示:

    >>> sorted(zip(l1,l2), key=lambda t: t[1])
    [('Apartment 3', '10 GBP'), ('Apartment 1', '15 GBP'), ('Apartment 2', '20 GBP')]
    

    如果你想在数字上做同样的事情,你可以做如下的事情:

    >>> sorted(zip(l1,l2), key=lambda t: float(t[1].split()[0]))