我写了一个Airbnb抓取器,它遍历指定位置的主页列表的每个子页面,对于每个子页面,它返回如下的zip对象:
subpage = zip(names, prices)
抓取单个子页面后,我将subpage
zip 对象添加到列表中:
all_subpages.append(subpage)
所以最后all_subpages
是一个zip对象列表,每个对象都包含一个子页面的数据。
我的问题是我想以HTML表格形式显示来自all_subpages
的数据,并且我希望这些数据按价格排序。
所以我的问题是:如何打印按价格订购all_subpages
的内容?
预期产出:
Name Price
Apartment 3 10 GBP
Apartment 1 15 GBP
Apartment 2 20 GBP
etc.
我对这个问题的看法:
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 numbertprice')
for (name, price) in sorted(chain.from_iterable(all_subpages), key=lambda v: int(v[1])):
print(f'{name}tt{price} GBP')
输出:
Home number price
82 1 GBP
11 2 GBP
3 10 GBP
78 15 GBP
1 20 GBP
33 100 GBP
给定:
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]))